请先阅读Private APIs not usable in Java 9?。
环境要求,[JDK1.6, JDK1.8]或JDK9及以上包含模块jdk.unsupported。
首先,创建一个Java工程,并创建Target类,Utils类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
public class Target{ public final String field; public static final String staticField; static{ staticField="B"; } public Target(){ field="a"; } public void print(){ System.out.println(field); } public static void printStatic(){ System.out.println(staticField); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
import sun.misc.Unsafe; import java.lang.reflect.Field; public class Utils{ private static Unsafe unsafe; public static Unsafe getUnsafe() { if(unsafe!=null) return unsafe; try { Field f = Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); unsafe = (Unsafe) f.get(null); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } if(unsafe==null) throw new NullPointerException(); return unsafe; } }
|
创建修改动态对象的类ModifyDynamic
1 2 3 4 5 6 7 8 9 10 11
| import java.lang.reflect.Field; public class ModifyDynamic{ public static void main(String[] args) throws Exception{ Target target = new Target(); target.print(); Field f=Target.class.getDeclaredField("field"); long offset=Utils.getUnsafe().objectFieldOffset(f); Utils.getUnsafe().putObjectVolatile(target,offset,"Z"); target.print(); } }
|
动态对象修改结果
1 2 3 4
| # java ModifyDynamic a Z #
|
创建修改静态对象的类ModifyStatic
1 2 3 4 5 6 7 8 9 10 11
| import java.lang.reflect.Field; public class ModifyStatic{ public static void main(String[] args) throws Exception{ target.printStatic(); Field f=Target.class.getDeclaredField("staticField"); long offset=Utils.getUnsafe().staticFieldOffset(f); Object o=Utils.getUnsafe().staticFieldBase(f); Utils.getUnsafe().putObjectVolatile(o,offset,"y"); target.printStatic(); } }
|
静态对象修改结果
1 2 3 4
| # java ModifyStatic B y #
|