使用反射访问成员变量

3

我有一个Class A,它有一个私有的、不可变的成员变量,这个成员变量是另一个Class B的对象。

Class A {
  private final classB obj;
}

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

}

我知道类A是单例模式。我需要使用类B中的“methodSet”方法设置一个值。我尝试访问类A,并在类A中获取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);

在这里我遇到了一个异常。

我不是很擅长反射。如果有人能提供解决方案或指出问题,我会非常感激。


你遇到了什么类型的异常? - Prasad S Deshpande
1个回答

5

我不确定你所说的“remote”反射的意思,即使对于反射,你也必须手上有对象实例。

你需要在某处获得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");

}

希望这有所帮助


谢谢您的回复。我有点困惑。所以,我不想创建A的新实例。我想访问A的当前实例并获取其中B的实例,然后设置它的值。这样做会创建A的新实例吗? - 12rad
不,你不需要创建额外的实例。你可以将反射视为对对象进行内省和操作的机制。通常情况下,通过正确使用面向对象编程(OOP),你可以实现类似的效果,但有时候你需要额外的灵活性,在这种情况下,反射可能是正确的工具。 - Mark Bramnik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接