我想使用Java反射调用私有方法和字段。以下是我的代码:
package javaReflect.test;
public class PrivateCar {
private String color;
protected void drive() {
System.out.println("this is private car! the color is:" + color);
}
}
package javaReflect.test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class PrivateCarReflect {
public static void main(String[] args) throws Throwable {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class clazz = loader.loadClass("javaReflect.test.PrivateCar");
PrivateCar pcar = (PrivateCar) clazz.newInstance();
Field colorFld = clazz.getDeclaredField("color");
colorFld.setAccessible(true);
colorFld.set(pcar, "red");
Method driveMtd = clazz.getDeclaredMethod("drive");
driveMtd.setAccessible(true);
driveMtd.invoke(pcar, (Object[]) null);
}
}
我执行了主要的方法,结果是this is private car! the color is:red
。但是当我更改调用序列方法和字段时。像这样:
Method driveMtd = clazz.getDeclaredMethod("drive");
driveMtd.setAccessible(true);
driveMtd.invoke(pcar, (Object[]) null);
Field colorFld = clazz.getDeclaredField("color");
colorFld.setAccessible(true);
colorFld.set(pcar, "red");
首先使用反射来调用方法。结果是:
this is private car! the color is:null.
我不知道为什么会这样。到底发生了什么?
在设置值之前访问变量。如果没有Reflection,它看起来像:
PrivateCar car = new PrivateCar();
car.drive(); //color is still null
car.color = "red";
使用反射不会改变此顺序。
毫无疑问,您的工作示例就像
PrivateCar car = new PrivateCar();
car.color = "red";
car.drive(); //color is 'red'
您应该在测试之前设置颜色。这就是为什么第二个代码片段没有达到您预期的效果。在正确设置字段之前,不能为其使用值,因此在选择它之前,不应该使用它调用方法