Remove illegal reflection access warnings on Field#modifiers

This commit is contained in:
IzzelAliz 2020-02-01 15:33:16 +08:00
parent e50bede493
commit 3ccdfb7abb

View File

@ -32,6 +32,7 @@ public class Ref {
public static final int ACC_SYNTHETIC = 0x1000; public static final int ACC_SYNTHETIC = 0x1000;
private static final Unsafe UNSAFE; private static final Unsafe UNSAFE;
private static final MethodHandles.Lookup LOOKUP; private static final MethodHandles.Lookup LOOKUP;
private static final long modifiersOffset;
static { static {
try { try {
@ -40,6 +41,7 @@ public class Ref {
Object lookupBase = UNSAFE.staticFieldBase(lookupField); Object lookupBase = UNSAFE.staticFieldBase(lookupField);
long lookupOffset = UNSAFE.staticFieldOffset(lookupField); long lookupOffset = UNSAFE.staticFieldOffset(lookupField);
LOOKUP = (MethodHandles.Lookup) UNSAFE.getObject(lookupBase, lookupOffset); LOOKUP = (MethodHandles.Lookup) UNSAFE.getObject(lookupBase, lookupOffset);
modifiersOffset = UNSAFE.objectFieldOffset(Field.class.getDeclaredField("modifiers"));
} catch (Throwable t) { } catch (Throwable t) {
throw new IllegalStateException("Unsafe not found"); throw new IllegalStateException("Unsafe not found");
} }
@ -208,9 +210,7 @@ public class Ref {
public static void forcedAccess(Field field) { public static void forcedAccess(Field field) {
try { try {
field.setAccessible(true); field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers"); getUnsafe().putInt(field, modifiersOffset, field.getModifiers() & ~Modifier.FINAL);
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
} catch (Throwable t) { } catch (Throwable t) {
t.printStackTrace(); t.printStackTrace();
} }