1、调用问题
我们直接获取Unsafe,调用其中属性方法时会出现异常:
java.lang.SecurityException: Unsafeat sun.misc.Unsafe.getUnsafe(Unsafe.java:90)at UnsafeTest.main(UnsafeTest.java:5)
异常分析:
Unsafe unsafe = Unsafe.getUnsafe();
上面这行代码出现的异常,获取Unsafe时出现异常,查看getUnsafe()方法如下:
@CallerSensitivepublic 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: Unsafepublic static Unsafe reflectGetUnsafe() throws NoSuchFieldException, IllegalAccessException {Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");theUnsafe.setAccessible(true);//禁止访问权限检查(访问私有属性时需要加上)return (Unsafe) theUnsafe.get(null);}