我有一个 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);
在这里我得到一个例外。
我不擅长反射。如果有人可以提出解决方案或指出问题所在,我将不胜感激。