简体   繁体   English

使用反射来调用字段上的方法

[英]Using reflection to invoke method on field

My code looks like the following: 我的代码如下所示:

class MyObject {

    MyField f = new MyField();

}

class MyField {
    public void greatMethod();
}

Is there a way to invoke the greatMethod() using reflection on a object of the class MyObject ? 有没有办法使用MyObject类对象的反射来调用greatMethod()

I tried the following: 我尝试了以下方法:

Field f = myObject.getClass().getDeclaredField("f");
Method myMethod = f.getDeclaringClass().getDeclaredMethod("greatMethod", new Class[]{});
myMethod.invoke(f);

But instead it is trying to call greatMethod() on my myObject directly and not on the field f in it. 但是它试图直接在我的myObject上调用greatMethod()而不是在其中的字段f上调用。 Is there a way to achieve this without need to modify the MyObject class (so that it would implement a method which calls the appropriate method on f). 有没有办法实现这一点,而无需修改MyObject类(因此它将实现一个在f上调用适当方法的方法)。

You were close yourself, you just need to get the declared method and invoke it on the instance of the field that is containted within your object instance, instead of the field, like below 你是亲密的,你只需要获取声明的方法并在对象实例中包含的字段的实例上调用它,而不是在字段中调用它,如下所示

    // 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM