Java: How to change the value of a private static final field
Previously I was working on a project with a lot of legacy code, one of my goals was to test parts of the “API”, in some cases I had to change the value of a “private static final” field.
I had to do this because this field was initialized by a JVM argument. It was initialized once when this class has been loaded, then it wasn’t modifiable anymore.
Using basic Java code it’s impossible to change this value, you have to use Java Reflection API. Let’s imagine you want to modify the value of the following field:
This field is declared in the class “Test”, here is the method that let us modify this const variable :
Here is the result when calling the above method:
In general that’s not a good practice to use that kind of code, I had to use it because:
I could not change the legacy code
for unit testing purposes so no impact on real code