I have a class with a private static final
field that, unfortunately, I need to change it at run-time.
Using reflection I get this error: java.lan
Many of the answers here are useful, but I've found none of them to work on Android
, in particular. I'm even a pretty hefty user of Reflect
by joor, and neither it nor apache's FieldUtils
- both mentioned here in some of the answers, do the trick.
The fundamental reason why this is so is because on Android there's no modifiers
field in the Field
class, which renders any suggestion involving this code (as in the marked answer), useless:
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
In fact, to quote from FieldUtils.removeFinalModifier()
:
// Do all JREs implement Field with a private ivar called "modifiers"?
final Field modifiersField = Field.class.getDeclaredField("modifiers");
So, the answer is no...
Pretty easy - instead of modifiers
, the field name is accessFlags
. This does the trick:
Field accessFlagsField = Field.class.getDeclaredField("accessFlags");
accessFlagsField.setAccessible(true);
accessFlagsField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
Side-note #1: this can work regardless of whether the field is static in the class, or not.
Side-note #2: Seeing that the field itself could be private, it's recommended to also enable access over the field itself, using
field.setAccessible(true)
(in addition toaccessFlagsField.setAccessible(true)
.