使用反射访问成员变量

12r*_*rad 3 java reflection

我有一个A类,它有一个私有的最终成员变量,它是另一个B类的对象.

Class A {
  private final classB obj;
}

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

}
Run Code Online (Sandbox Code Playgroud)

我知道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);
Run Code Online (Sandbox Code Playgroud)

在这里我得到一个例外.

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

Mar*_*nik 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");

}
Run Code Online (Sandbox Code Playgroud)

}

希望这可以帮助