【问题标题】:Using reflection to invoke method on field使用反射在字段上调用方法
【发布时间】:2014-05-20 16:53:06
【问题描述】:

我的代码如下所示:

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 上适当方法的方法)。

【问题讨论】:

  • 通过调用 getDeclaringClass 你得到了 MyObject 类,所以很清楚它为什么在 MyObject 中搜索方法。

标签: java reflection methods invoke


【解决方案1】:

您自己很接近,您只需要获取声明的方法并在对象实例中包含的字段的实例上调用它,而不是字段,如下所示

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

【讨论】:

  • 对不起,该字段在获取值之前应该可以访问,请查看更新回复
  • 没问题,很高兴我能帮上忙
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-15
  • 2012-08-08
相关资源
最近更新 更多