19

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?

3
  • You...can't change the modifiers on a class field at runtime. Commented Jun 25, 2012 at 8:26
  • 1
    I can according to that link. Commented Jun 25, 2012 at 19:21
  • 3
    Do remember that the Java compiler can inline values of primitive static final fields. Doing this sort of reflection magic could lead to bizarre behaviour. Commented Jun 27, 2012 at 20:28

1 Answer 1

11

This works for non-static fields.

Field field = data.getClass().getDeclaredField("type");
field.setAccessible(true);
field.set(data, null);
Sign up to request clarification or add additional context in comments.

3 Comments

This worked. But why? Does ART remove the final modifier or does it simple allow to access it anyway?
This works, because the first object in the field.set(...) function is the object to modify NOT the field
data is not static in this case?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.