3

我有一个 A 类,它有一个私有的 final 成员变量,它是另一个 B 类的对象。

Class A {
  private final classB obj;
}

Class B {
   public void methodSet(String some){
   }

}

我知道 A 类是一个单例。我需要使用 B 类中的方法“methodSet”设置一个值。我尝试访问 classA 并访问 classA 中的 ClassB 实例。

我这样做:

Field MapField = Class.forName("com.classA").getDeclaredField("obj");
MapField.setAccessible(true);
Class<?> instance = mapField.getType(); //get teh instance of Class B.
instance.getMethods()
//loop through all till the name matches with "methodSet"
m.invoke(instance, newValue);

在这里我得到一个例外。

我不擅长反射。如果有人可以提出解决方案或指出问题所在,我将不胜感激。

4

1 回答 1

5

我不确定“远程”反射是什么意思,即使对于反射,您也必须拥有该对象的实例。

您需要在某个地方获取 A 的实例。B 的实例也是如此。

这是您要实现的目标的工作示例:

package reflection;

class  A {
     private final B obj = new B();
}


class B {
    public void methodSet(String some) {
        System.out.println("called with: " + some);
    }
}


public class ReflectionTest {
    public static void main(String[] args) throws Exception{
       // create an instance of A by reflection
       Class<?> aClass = Class.forName("reflection.A");
       A a = (A) aClass.newInstance();

       // obtain the reference to the data field of class A of type B
       Field bField = a.getClass().getDeclaredField("obj");
       bField.setAccessible(true);
       B b = (B) bField.get(a);

       // obtain the method of B (I've omitted the iteration for brevity)
       Method methodSetMethod = b.getClass().getDeclaredMethod("methodSet", String.class);
       // invoke the method by reflection
       methodSetMethod.invoke(b, "Some sample value");

}

}

希望这可以帮助

于 2012-09-11T05:50:13.190 回答