我想使用Java反射调用私有方法和fields.Below是我的代码:
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.
我不知道为什么会这样.究竟发生了什么?
您在设置值之前访问变量.如果没有反射,那将是:
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'