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.lang.IllegalAccessException: Can not set static final boolean field
Is there any way to change the value?
Field hack = WarpTransform2D.class.getDeclaredField("USE_HACK");
hack.setAccessible(true);
hack.set(null, true);
Assuming no
SecurityManageris preventing you from doing this, you can usesetAccessibleto get aroundprivateand resetting the modifier to get rid offinal, and actually modify aprivate static finalfield.Here’s an example:
Assuming no
SecurityExceptionis thrown, the above code prints"Everything is true".What’s actually done here is as follows:
booleanvaluestrueandfalseinmainare autoboxed to reference typeBoolean"constants"Boolean.TRUEandBoolean.FALSEpublic static final Boolean.FALSEto refer to theBooleanreferred to byBoolean.TRUEfalseis autoboxed toBoolean.FALSE, it refers to the sameBooleanas the one refered to byBoolean.TRUE"false"now is"true"Related questions
static final File.separatorCharfor unit testingInteger‘s cache, mutating aString, etcCaveats
Extreme care should be taken whenever you do something like this. It may not work because a
SecurityManagermay be present, but even if it doesn’t, depending on usage pattern, it may or may not work.See also
private static final boolean, because it’s inlineable as a compile-time constant and thus the "new" value may not be observableAppendix: On the bitwise manipulation
Essentially,
turns off the bit corresponding to
Modifier.FINALfromfield.getModifiers().&is the bitwise-and, and~is the bitwise-complement.See also
Remember Constant Expressions
Still not being able to solve this?, have fallen onto depression like I did for it? Does your code looks like this?
Reading the comments on this answer, specially the one by @Pshemo, it reminded me that Constant Expressions are handled different so it will be impossible to modify it. Hence you will need to change your code to look like this:
if you are not the owner of the class… I feel you!
For more details about why this behavior read this?