简体   繁体   中英

Android: changing private static final field using java reflection

Change private static final field using Java reflection

I followed the instructions in the link above to change a private static final field using java reflection. I have an object named "data." Inside "data," there is a private static final variable named "type." I want to set "type" to be null. Here is my code.

Field field = data.getClass().getDeclaredField("type");
field.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
field.set(data, null);

I tried doing this on Java 1.7 with similar code and it worked. But running this code on Android produces the following error: java.lang.NoSuchFieldException: modifiers

I guess "modifiers" is not a field in the Field class on Android.

How do I fix this?

This works for non-static fields.

Field field = data.getClass().getDeclaredField("type");
field.setAccessible(true);
field.set(data, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM