Java還要再學一遍基礎(十五)獲取Unsafe
阿新 • • 發佈:2018-12-29
Java中的Unsafe被設計成我們不能隨便訪問,雖然也可以通過反射獲取,但是沒有經過嚴格測試的自己寫的程式碼不能保證它的正確性,這裡貼出谷歌api中的Unsafe獲取方法,以備後用:
private static sun.misc.Unsafe getUnsafe() { try { return sun.misc.Unsafe.getUnsafe(); } catch (SecurityException tryReflectionInstead) {} try { return java.security.AccessController.doPrivileged (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { public sun.misc.Unsafe run() throws Exception { Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; for (java.lang.reflect.Field f : k.getDeclaredFields()) { f.setAccessible(true); Object x = f.get(null); if (k.isInstance(x)) return k.cast(x); } throw new NoSuchFieldError("the Unsafe"); }}); } catch (java.security.PrivilegedActionException e) { throw new RuntimeException("Could not initialize intrinsics", e.getCause()); } }