Instantiating sun.misc.Unsafe via reflection
suggest changepublic static Unsafe getUnsafe() {
try {
Field unsafe = Unsafe.class.getDeclaredField("theUnsafe");
unsafe.setAccessible(true);
return (Unsafe) unsafe.get(null);
} catch (IllegalAccessException e) {
// Handle
} catch (IllegalArgumentException e) {
// Handle
} catch (NoSuchFieldException e) {
// Handle
} catch (SecurityException e) {
// Handle
}
return null;
}
sun.misc.Unsafe has a private constructor, and getUnsafe() allows the call only when the caller’s class loader is the bootstrap class loader. Reflection can read the static theUnsafe field instead. On Java 9 and later, setAccessible may be denied for this JDK-internal field. The return null path is required; without it the method does not compile.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents