unsafe icon indicating copy to clipboard operation
unsafe copied to clipboard

"theUnsafe" field in Unsafe APILevel 16

Open anuchandy opened this issue 5 years ago • 0 comments

I was trying to use the library in "Nexus 4 API Level 16" and the following block throws NoSuchElement for theUnsafe field

static {
    try {
        final Field field = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        unsafe = (Unsafe) field.get(null);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

saw that backport libs such as retrostream handles NSFE in following way:

static {
    try {
        Field field = null;
        try {
            field = Unsafe.class.getDeclaredField("theUnsafe");
        } catch (NoSuchFieldException oldAndroid) {
            field = Unsafe.class.getDeclaredField("THE_ONE");
        }
        field.setAccessible(true);
        unsafe = (Unsafe) field.get(null);
    } catch (Exception e) {
        throw new Error(e);
    }
}

anuchandy avatar Nov 13 '20 19:11 anuchandy