JDK9+ Method.class.getDeclaredFields() Method实例将不能再直接通过反射修改
JDK9+更安全了,以下代码示例,原因见截图
Test Code
import sun.reflect.Reflection;import java.lang.reflect.Field;
import java.lang.reflect.Method;public class Base {public static void main(String[] args) throws Exception {Method m = Class1.class.getDeclaredMethod("getName");m.setAccessible(true);System.out.println(m.invoke(new Class1()));Class2 clazz2 = new Class2();/* jdk9+, return empty array */Field[] fields = Method.class.getDeclaredFields();/* jdk9+, failed */Field f = Method.class.getDeclaredField("clazz");f.setAccessible(true);/* replace the "getName" method field clazz from Class1 ot Class2 */f.set(m, clazz2.getClass());System.out.println(m.invoke(clazz2));}static class Class1 {public String getName() {return "Sub1";}}static class Class2 {public String getName() {return "Sub2";}}
}
Reflection.class
JDK8 的Reflection
500