简体   繁体   English

使用反射访问成员变量

[英]Access a member variable using reflection

I have a Class A, which has a private final member variable which is an object of another class B. 我有一个A类,它有一个私有的最终成员变量,它是另一个B类的对象。

Class A {
  private final classB obj;
}

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

}

I know that class A is a singleton . 我知道A级是单身人士。 I need to set a value using the method "methodSet" in class B. I try and access classA and get access to the instance of ClassB in classA . 我需要使用类B中的方法“methodSet”设置一个值。我尝试访问classA并访问classA中的ClassB实例。

I do this: 我这样做:

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

Here I get an exception. 在这里我得到一个例外。

I am not proficient at Reflection. 我不擅长反思。 I would appreciate if somebody could suggest a solution or point what's wrong. 如果有人能提出解决方案或指出什么是错的,我将不胜感激。

I'm not sure what do you mean by ''remote'' reflection, even for reflection you must have an instance of the object in your hands. 我不确定“远程”反射是什么意思,即使是反射你也必须拥有一个物体实例。

Somewhere you need to obtain an instance of A. The same holds for the instance of B. 在某处你需要获得A的实例。同样适用于B的实例。

Here is a working example of what you're trying to achieve: 以下是您要实现的目标的实例:

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

}

} }

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM