Java-Unsafe类(一)

来源:互联网 发布:快典网藏头诗软件 编辑:程序博客网 时间:2024/06/13 10:18

1、 sun.misc.Unsafe 提供了可随意查看及修改JVM中运行时的数据结构
2、

import sun.misc.Unsafe; // Eclipse引入此行会出现错误提示, 解决方法: [方法](http://blog.csdn.net/fenglibing/article/details/17138079)public class Test {    public static void main(String args[]) throws Exception{        Field f = Unsafe.class.getDeclaredField("theUnsafe");        f.settAccessible(true);        Unsafe unsafe = (Unsafe)f.get(null);        Player p = (Player)unsafe.allocateInstance(Player.class);        p.setAge(45);        unsafe.allocateMemory(0L);        unsafe.freeMemory(0L)l        unsafe.compareAndSwapInt(...);    }}class Player {    private int age = 12;    private Player () {        this.age = 50;    }    public int getAge() {return this.age;}    public void setAge(int age) {this.age = age;}}

参考: 参考1