使用反射访问成员变量

时间:2012-09-11 05:40:33

标签: java reflection

我有一个A类,它有一个私有的最终成员变量,它是另一个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);

我在这里得到一个例外。

我不擅长反思。如果有人能提出解决方案或指出什么是错的,我将不胜感激。

1 个答案:

答案 0 :(得分: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");

}

}

希望这有帮助

相关问题