unsafe
unsafe copied to clipboard
"theUnsafe" field in Unsafe APILevel 16
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);
}
}