0

I have a class:

public class MyClass {

  private final AnotherClass myField = new AnotherClass() {
       @Override
       public long getSize() { 
            ...
       }
}

I have already got the Class object of MyClass:

Class<MyClass> myClazz = LOAD_CLASS("MyClass");

how to use Java reflection to invoke the getSize() method of myField defined in MyClass ?

Leem.fin
  • 40,781
  • 83
  • 202
  • 354
  • See: http://stackoverflow.com/questions/10638826/java-reflection-impact-of-setaccessibletrue , but be cautious. – Kevin Bowersox Jan 08 '14 at 14:00
  • @Kevin, I don't see how your link answers my question. My question is not only on how to load the field, but also how to call the getSize() function of the field. – Leem.fin Jan 08 '14 at 14:05
  • It describes how to set the accessibility of the field, which will allow you to access a private field via reflection. – Kevin Bowersox Jan 08 '14 at 14:16
  • @Kevin, I see that, but my key question is how to invoke the function of private field, your link has no reference on that. – Leem.fin Jan 08 '14 at 14:20

2 Answers2

1

You will have to use the Field#setAccessible(boolean b) method in order to get access on the private field.

You can do :

MyClass obj = new MyClass();
try {
    Field field = obj.getClass().getDeclaredField("myField");
    field.setAccessible(true);
    AnotherClass privateField = (AnotherClass) field.get(obj);
    long size = privateField.getSize(); //invoke the getSize() method
    field.setAccessible(false);
} catch (NoSuchFieldException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
}
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • But I am not able to declare AnotherClass type like your code shows, because I need to load everything at runtime, not compile time – Leem.fin Jan 08 '14 at 14:18
  • 1
    @KevinBowersox The accessability is only set for that Field instance, and future calls to getDeclaredFields return new instances. So you can just let it go out of scope, and you'll be fine. – yshavit Jan 08 '14 at 14:31
1

You need to use getDeclaredMethod on the myField object:

Field field = obj.getClass().getDeclaredField("myField");
field.setAccessible(true);

Object privateField = field.get(obj);

Method getSizeMethod = privateField.getClass().getDeclaredMethod("getSize");

Long result = (Long)getSizeMethod.invoke(privateField);
greg-449
  • 109,219
  • 232
  • 102
  • 145