pri*_*ewo 9 java reflection methods invoke
我的代码如下所示:
class MyObject {
MyField f = new MyField();
}
class MyField {
public void greatMethod();
}
Run Code Online (Sandbox Code Playgroud)
有没有办法greatMethod()在类的对象上调用using反射MyObject?
我尝试了以下方法:
Field f = myObject.getClass().getDeclaredField("f");
Method myMethod = f.getDeclaringClass().getDeclaredMethod("greatMethod", new Class[]{});
myMethod.invoke(f);
Run Code Online (Sandbox Code Playgroud)
但是它试图greatMethod()直接调用我的myObject,而不是调用其中的字段f.有没有办法实现这一点,而无需修改MyObject类(因此它将实现一个在f上调用适当方法的方法).
Mor*_*fic 18
你是亲密的,你只需要获取声明的方法并在对象实例中包含的字段的实例上调用它,而不是在字段中调用它,如下所示
// obtain an object instance
MyObject myObjectInstance = new MyObject();
// get the field definition
Field fieldDefinition = myObjectInstance.getClass().getDeclaredField("f");
// make it accessible
fieldDefinition.setAccessible(true);
// obtain the field value from the object instance
Object fieldValue = fieldDefinition.get(myObjectInstance);
// get declared method
Method myMethod =fieldValue.getClass().getDeclaredMethod("greatMethod", new Class[]{});
// invoke method on the instance of the field from yor object instance
myMethod.invoke(fieldValue);
Run Code Online (Sandbox Code Playgroud)