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
?
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();
}
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.