【问题标题】:Access a member variable using reflection使用反射访问成员变量
【发布时间】:2012-09-04 00:13:15
【问题描述】:

我有一个 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);

在这里我得到一个例外。

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

【问题讨论】:

  • 你遇到什么样的异常?

标签: java reflection


【解决方案1】:

我不确定你所说的“远程”反射是什么意思,即使是反射,你也必须有一个对象的实例。

您需要在某个地方获取 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 的当前实例并在 A 中获取 B 的实例,然后设置它的值。我不会在这里创建一个新的 A 实例吗?
  • 不,您不创建额外的实例。您可以将反射视为自省和操作对象的一种机制。通常你可以通过正确使用 OOP 来达到类似的效果,但有时你需要额外的灵活性,在这种情况下反射可能是正确使用的工具
猜你喜欢
  • 2018-05-21
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
  • 1970-01-01
相关资源
最近更新 更多