我刚试了一下,JDK 7 中可以使用。既然这个类叫 Unsafe 类,那使用时请谨慎。其中的 API 可以巅覆掉之前 Java 中的一些概念!import java.lang.reflect.Field;public class UnsafeTest { @SuppressWarnings("restriction") private static final sun.misc.Unsafe UNSAFE = getUnsafe(); public static void main(String[] args) throws InstantiationException { Player p = (Player) UNSAFE.allocateInstance(Player.class); System.out.println(p.getAge()); p.setAge(45); System.out.println(p.getAge()); System.out.println(new Player().getAge()); } @SuppressWarnings("restriction") private static sun.misc.Unsafe getUnsafe() { try { Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe"); f.setAccessible(true); return (sun.misc.Unsafe) f.get(null); } catch(Exception e) { throw new IllegalStateException( "Unsafe initialize failed" , e ); } }
public static class Player{ private int age = 12; public Player(){ this.age = 50; } public int getAge(){ return this.age; } public void setAge(int age){ this.age = age; } } } 上面这个例子一个典型的巅覆构造 Java 对象的示例,挺有意思的!
private static final sun.misc.Unsafe UNSAFE = getUnsafe(); public static void main(String[] args) throws InstantiationException {
Player p = (Player) UNSAFE.allocateInstance(Player.class);
System.out.println(p.getAge());
p.setAge(45);
System.out.println(p.getAge());
System.out.println(new Player().getAge());
} @SuppressWarnings("restriction")
private static sun.misc.Unsafe getUnsafe() {
try {
Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
return (sun.misc.Unsafe) f.get(null);
}
catch(Exception e) {
throw new IllegalStateException( "Unsafe initialize failed" , e );
}
}
public static class Player{
private int age = 12;
public Player(){
this.age = 50;
}
public int getAge(){
return this.age;
}
public void setAge(int age){
this.age = age;
}
}
}
上面这个例子一个典型的巅覆构造 Java 对象的示例,挺有意思的!