unsafe中方法的使用

创建目标对象

    static class Simple{
        private long l = 0;
        
        public Simple() {
            this.l = 1;
            System.out.println("==================");
        }
        
        public long get() {
            return this.l;
        }
    }

创建对象实例的三种方法

方法一:

Simple simple1 = new Simple();
System.out.println(simple1.get());

方法二:

        Simple simple2 = Simple.class.newInstance();
        System.out.println(simple2.get());

方法三:

        //绕过了类的初始化阶段
        Class<?> simple3 = Class.forName("com.dwz.atomicApi.UnsafeFooTest$Simple");

创建unsafe:

    private static Unsafe getUnsafe() {
        try {
            Field f = Unsafe.class.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            return (Unsafe) f.get(null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } 
    }

使用unsafe来绕过构造方法创建对象:

        Unsafe unsafe = getUnsafe();
        //开辟内存
        Simple simple4 = (Simple)unsafe.allocateInstance(Simple.class);
        System.out.println(simple4.get());
        System.out.println(simple4.getClass());
        System.out.println(simple4.getClass().getClassLoader());

结果如下:

0
class com.dwz.atomicApi.UnsafeFooTest$Simple
sun.misc.Launcher$AppClassLoader@73d16e93

猜你喜欢

转载自www.cnblogs.com/zheaven/p/13181996.html
今日推荐