繁体   English   中英

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

[英]Using reflection to invoke method on field

我的代码如下所示:

class MyObject {

    MyField f = new MyField();

}

class MyField {
    public void greatMethod();
}

有没有办法使用MyObject类对象的反射来调用greatMethod()

我尝试了以下方法:

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

但是它试图直接在我的myObject上调用greatMethod()而不是在其中的字段f上调用。 有没有办法实现这一点,而无需修改MyObject类(因此它将实现一个在f上调用适当方法的方法)。

你是亲密的,你只需要获取声明的方法并在对象实例中包含的字段的实例上调用它,而不是在字段中调用它,如下所示

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