Unsafe的使用

1、调用问题

我们直接获取Unsafe,调用其中属性方法时会出现异常:

java.lang.SecurityException: Unsafe
	at sun.misc.Unsafe.getUnsafe(Unsafe.java:90)
	at UnsafeTest.main(UnsafeTest.java:5)

在这里插入图片描述
异常分析:

Unsafe unsafe = Unsafe.getUnsafe();

上面这行代码出现的异常,获取Unsafe时出现异常,查看getUnsafe()方法如下:

	@CallerSensitive
    public static Unsafe getUnsafe() {
        Class var0 = Reflection.getCallerClass();
        if (!VM.isSystemDomainLoader(var0.getClassLoader())) {
            throw new SecurityException("Unsafe");
        } else {
            return theUnsafe;
        }
    }

如上getUnsafe()被设计成只能从启动类加载器(Bootstrap Class Loader)加载,所以我们自己直接调用时会出现异常。

2、如何调用

	//引用Unsafe需使用如下反射方式,否则会抛出异常java.lang.SecurityException: Unsafe
    public static Unsafe reflectGetUnsafe() throws NoSuchFieldException, IllegalAccessException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);//禁止访问权限检查(访问私有属性时需要加上)
        return (Unsafe) theUnsafe.get(null);
    }

在这里插入图片描述


版权声明:本文为qq_16268979原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。