Instantiating sun.misc.Unsafe via reflection

suggest change
public 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents