package c; public class So { private final String name= "sss"; //如果String创建时new的话,反射就能改变 //private final String name= new String("sss"); public void t(){ System.out.println(name); } } package c; import java.lang.reflect.Field; public class Test { public static void main(String[] args) throws Exception { Class c = So.class; Field field = c.getDeclaredField( "name"); field.setAccessible(true); So so = new So(); System.out.println(field.get(so)); field.set(so, "aa"); System.out.println(field.get(so)); so.t(); } }
现在的运行结果为
sss
aa
sss
如果String name 通过new创建的话就下面这样
sss
aa
aa