我不确定“远程”反射是什么意思,即使是反射你也必须拥有一个物体实例.
在某处你需要获得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");
}
}
希望这可以帮助