[英]Class can't access its own protected member variable using reflection from different package
[英]Access a member variable using reflection
我有一個A類,它有一個私有的最終成員變量,它是另一個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);
在這里我得到一個例外。
我不擅長反思。 如果有人能提出解決方案或指出什么是錯的,我將不勝感激。
我不確定“遠程”反射是什么意思,即使是反射你也必須擁有一個物體實例。
在某處你需要獲得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");
}
}
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.