Java
Programming
Reflection
Static Final Field
Software Development

Change a private static final field using Java reflection

Codemia Knowledge Hub ·

Java reflection can modify a private static final field, but how depends on your JDK. On JDK 8 and earlier you can strip the final modifier through the modifiers field hack. JDK 9 through 11 still allow it with warnings. JDK 12 removed the modifiers field from java.lang.reflect.Field, and from JDK 16 strong encapsulation blocks the workaround by default.

So the technique is only reliable on older JDKs. On modern Java you need VarHandle, MethodHandles.Lookup or --add-opens flags, and even those are increasingly restricted. The history matters because a lot of legacy code and Stack Overflow answers still use the old approach.

Why people want to do this

  • Testing: overriding a constant (a timeout, feature flag or endpoint URL) in unit tests without touching production code.
  • Legacy codebases: changing configuration constants in third-party libraries that expose no setter.
  • Framework internals: some frameworks (older versions of Spring, Guice) use reflection to inject values into final fields.

It is always a workaround, not a recommended pattern. If you control the code, pass configuration through constructors or configuration objects instead.

The modifiers hack (JDK 8 and earlier)

This is the technique most tutorials show. It reads the modifiers field of java.lang.reflect.Field itself and clears the FINAL bit:

java
1import java.lang.reflect.Field;
2import java.lang.reflect.Modifier;
3
4public class ReflectionDemo {
5    private static final String CONFIG_URL = new String("https://default.example.com");
6
7    public static void main(String[] args) throws Exception {
8        System.out.println("Before: " + CONFIG_URL);
9
10        Field field = ReflectionDemo.class.getDeclaredField("CONFIG_URL");
11        field.setAccessible(true);
12
13        // Remove the final modifier
14        Field modifiersField = Field.class.getDeclaredField("modifiers");
15        modifiersField.setAccessible(true);
16        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
17
18        // Set the new value (null for static fields)
19        field.set(null, "https://test.example.com");
20
21        System.out.println("After: " + CONFIG_URL);
22    }
23}

On JDK 8 this prints:

text
Before: https://default.example.com
After: https://test.example.com
StepAPI CallPurpose
1. Get the target fieldgetDeclaredField("CONFIG_URL")Access the field regardless of visibility
2. Make it accessiblefield.setAccessible(true)Bypass private access check
3. Get the modifiers fieldField.class.getDeclaredField("modifiers")Access Field's own internal modifiers int
4. Strip FINALmodifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL)Clear the final bit using bitwise AND with NOT
5. Set new valuefield.set(null, "https://test.example.com")First arg is null because the field is static

Compile-time constants are inlined

Primitive and String constants have a critical catch. When the value is known at compile time, the compiler inlines it into every place it is used. Reflection changes the field, but the inlined copies keep the old value.

java
1public class InlineDemo {
2    private static final int TIMEOUT = 30;         // Compile-time constant
3    private static final Integer TIMEOUT_OBJ = 30; // NOT a compile-time constant
4
5    public static void main(String[] args) throws Exception {
6        // Change TIMEOUT via reflection...
7        // System.out.println(TIMEOUT) still prints 30
8        // because the compiler replaced TIMEOUT with the literal 30
9    }
10}

This applies to String literals and to int, long, double, float, boolean, char, short and byte fields assigned a literal or constant expression. The reflective view of the field changes, but the compiled bytecode already has the old value baked in.

To avoid it, initialize the field with a non-constant expression:

java
private static final String CONFIG_URL = System.getenv("DEFAULT_URL");
// This is NOT a compile-time constant, so reflection works as expected

Behavior by JDK version

JDK Versionmodifiers Field HackVarHandle--add-opens RequiredNotes
8 and earlierWorksN/ANoNo warnings
9 to 11Works with warningsAvailable (JDK 9+)No (but recommended)Illegal reflective access warning
12 to 15Fails (NoSuchFieldException)Works with --add-opensYes for cross-module accessmodifiers field removed from Field
16+FailsRestricted by defaultYes, mandatoryStrong encapsulation enforced

Options on modern JDKs

VarHandle (JDK 9+)

VarHandle gives a cleaner field-access API, but for final fields in modules you don't own it still needs --add-opens:

java
1import java.lang.invoke.MethodHandles;
2import java.lang.invoke.VarHandle;
3import java.lang.reflect.Field;
4
5public class VarHandleDemo {
6    private static final String CONFIG_URL = new String("https://default.example.com");
7
8    public static void main(String[] args) throws Exception {
9        // Requires: --add-opens java.base/java.lang.reflect=ALL-UNNAMED
10        var lookup = MethodHandles.privateLookupIn(
11            Field.class, MethodHandles.lookup()
12        );
13
14        VarHandle modifiers = lookup.findVarHandle(
15            Field.class, "modifiers", int.class
16        );
17
18        Field field = VarHandleDemo.class.getDeclaredField("CONFIG_URL");
19        field.setAccessible(true);
20
21        int mods = field.getModifiers();
22        modifiers.set(field, mods & ~java.lang.reflect.Modifier.FINAL);
23
24        field.set(null, "https://test.example.com");
25        System.out.println(CONFIG_URL);
26    }
27}

The --add-opens JVM flag

On JDK 16+ you must pass explicit module-opening flags:

bash
java --add-opens java.base/java.lang.reflect=ALL-UNNAMED \
     --add-opens java.base/java.lang=ALL-UNNAMED \
     VarHandleDemo

Without them privateLookupIn fails with IllegalAccessException, because java.base does not open java.lang.reflect.

Test frameworks instead of reflection

For tests, the most common case, frameworks offer safer options:

java
1// Mockito (static mocking, requires mockito-inline or mockito 5+)
2try (var mock = mockStatic(ConfigClass.class)) {
3    mock.when(ConfigClass::getTimeout).thenReturn(60);
4    // test logic
5}
java
1// Spring Test
2@TestPropertySource(properties = "app.timeout=60")
3class MyServiceTest {
4    // Spring injects the overridden value
5}

These avoid reflection completely and are unaffected by JDK changes.

When reflecting on final fields is justified

Rarely, but there are legitimate cases:

  • Deserializers and ORM frameworks that rebuild objects from external data must set final fields during construction. Gson and Jackson use setAccessible internally for this.
  • Security research and instrumentation tools need deep reflective access by design.
  • Legacy integration where the source can't change and there is no configuration API.

Otherwise, redesign the code to take values through constructors, configuration objects or dependency injection.

Mistakes to avoid

  • Expecting compile-time constants to change everywhere. static final primitives and String literals are inlined by the compiler, so every compiled use site keeps the old value even after reflection changes the field.
  • Testing on JDK 8 and deploying on JDK 17+. The hack works on 8, throws NoSuchFieldException on 12+ and InaccessibleObjectException on 16+. Test reflective code on your production JDK.
  • Using field.set(null, value) for instance fields. null works only for static fields; for instance fields pass the object.
  • Not restoring values after tests. A modified static final field leaks into later tests in the same JVM and makes the suite flaky.
  • Using getField instead of getDeclaredField. getField returns only public fields; private fields need getDeclaredField.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms