To access a private field you need to set Field::setAccessible to true. You can pull the field off the super class. This code works:

CopyClass<?> clazz = Child.class;
Object cc = clazz.newInstance();

Field f1 = cc.getClass().getSuperclass().getDeclaredField("a_field");
f1.setAccessible(true);
f1.set(cc, "reflecting on life");
String str1 = (String) f1.get(cc);
System.out.println("field: " + str1);
Answer from John McClean on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › set field value with reflection
Set Field Value With Reflection | Baeldung
January 8, 2024 - Learn how to set values of private fields in Java using the Reflection API.
🌐
Jenkov
jenkov.com › tutorials › java-reflection › private-fields-and-methods.html
Java Reflection - Private Fields and Methods
April 9, 2018 - Here is a simple example of a class with a private field, and below that the code to access that field via Java Reflection: public class PrivateObject { private String privateString = null; public PrivateObject(String privateString) { this.privateString = privateString; } } PrivateObject privateObject = new PrivateObject("The Private Value"); Field privateStringField = PrivateObject.class. getDeclaredField("privateString"); privateStringField.setAccessible(true); String fieldValue = (String) privateStringField.get(privateObject); System.out.println("fieldValue = " + fieldValue);
🌐
Intertech
intertech.com › home › using spring’s reflectionutils to access private fields
Using Spring's ReflectionUtils to Access Private Fields - Intertech
February 13, 2024 - 3. Using reflection, set the field’s accessible flag to true so we can then set the field’s value. The accessible flag toggles reflection access to Java internals, such as fields. This step uses the Spring ReflectionUtils.makeAccessible method.
🌐
W3Schools Blog
w3schools.blog › get-set-private-field-value-in-java
Java reflection get set private field value – W3schools
The get() and set() method are used to get and set public field value in java. Note: We have to turn off the java access check for field modifiers. ... package com.w3spoint; import java.lang.reflect.Field; public class ReflectionTest { public static void main(String args[]){ try { TestClass ...
🌐
Blogger
javarevisited.blogspot.com › 2012 › 05 › how-to-access-private-field-and-method.html
How to access Private Field and Method Using Reflection in Java? Example Tutorial
In the last article, we have seen details about private keywords in Java and learned why we should always make fields and methods private in Java. There we have mentioned that private fields and methods are only accessible in the class they are declared but with reflection, you can call the private method and access private fields outside the class.
🌐
Java: How To Do It
javahowtodoit.wordpress.com › 2014 › 08 › 28 › how-to-write-value-to-private-field-using-java-reflection
How to get and set private field using Java reflection | Java: How To Do It
September 12, 2014 - // Class declaration class MyClass1 { private String instanceField = "A"; public String getInstanceField() { return instanceField; } } // Given object MyClass1 object = new MyClass1(); // Get field instance Field field = MyClass1.class.getDeclaredField("instanceField"); field.setAccessible(true); // Suppress Java language access checking // Get value String fieldValue = (String) field.get(object); System.out.println(fieldValue); // -> A // Set value field.set(object, "B"); System.out.println(object.getInstanceField()); // -> B
🌐
Java2s
java2s.com › example › java › reflection › set-private-field-value-via-reflection.html
Set Private field value via reflection - Java Reflection
import java.lang.reflect.Field; public class FieldTroubleToo { public final boolean b = true; public static void main(String... args) { FieldTroubleToo ft = new FieldTroubleToo(); try {//from w ww .j a v a 2 s . c o m Class<?> c = ft.getClass(); Field f = c.getDeclaredField("b"); // f.setAccessible(true); // solution f.setBoolean(ft, Boolean.FALSE); // IllegalAccessException // production code should handle these exceptions more gracefully } catch (NoSuchFieldException x) { x.printStackTrace(); } catch (IllegalArgumentException x) { x.printStackTrace(); } catch (IllegalAccessException x) { x.printStackTrace(); } } } /* * Copyright (c) 1995, 2008, Oracle and/or its affiliates.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-access-private-field-and-method-using-reflection-in-java
How to Access Private Field and Method Using Reflection in Java? - GeeksforGeeks
February 5, 2021 - // Access Private Field Using Reflection in Java import java.lang.reflect.Field; // Student class declaration class Student { // private fields private String name; private int age; // Constructor public Student(String name, int age) { this.name = name; this.age = age; } // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } private int getAge() { return age; } public void setAge(int age) { this.age = age; } // Override toString method to get required // output at terminal @Override public String toString() { return "Employee [nam
Find elsewhere
🌐
Baeldung
baeldung.com › home › java › core java › reading the value of ‘private’ fields from a different class in java
Reading the Value of 'private' Fields from a Different Class in Java | Baeldung
November 13, 2025 - public class Person { private String ... // getters and setters } To make any private field accessible, we have to call the Field#setAccessible method:...
Top answer
1 of 4
73

This answer is more than exhaustive on the topic.

JLS 17.5.3 Subsequent Modification of Final Fields

Even then, there are a number of complications. If a final field is initialized to a compile-time constant in the field declaration, changes to the final field may not be observed, since uses of that final field are replaced at compile time with the compile-time constant.

But, if you read the paragraph above very carefully, you may find a way around here (set the private final field in the constructor instead of in the field definition):

import java.lang.reflect.Field;


public class Test {

  public static void main(String[] args) throws Exception {
    WithPrivateFinalField pf = new WithPrivateFinalField();
    System.out.println(pf);
    Field f = pf.getClass().getDeclaredField("s");
    f.setAccessible(true);
    System.out.println("f.get(pf): " + f.get(pf));
    f.set(pf, "No, you’re not!");
    System.out.println(pf);
    System.out.println("f.get(pf): " + f.get(pf));
  }

  private static class WithPrivateFinalField {
    private final String s;

    public WithPrivateFinalField() {
      this.s = "I’m totally safe";
    }
    public String toString() {
      return "s = " + s;
    }
  }

}

The output is then as follows:

s = I’m totally safe
f.get(pf): I’m totally safe
s = No, you’re not!
f.get(pf): No, you’re not!

Hope this helps a bit.

2 of 4
18

This

class WithPrivateFinalField {
    private final String s = "I’m totally safe";
    public String toString() {
        return "s = " + s;
    }  
} 

actually compiles like this:

class WithPrivateFinalField {
    private final String s = "I’m totally safe";
    public String toString() {
        return "s = I’m totally safe";
    }  
}

That is, compile-time constants get inlined. See this question. The easiest way to avoid inlining is to declare the String like this:

private final String s = "I’m totally safe".intern();

For other types, a trivial method call does the trick:

private final int integerConstant = identity(42);
private static int identity(int number) {
    return number;
}
🌐
Medium
medium.com › @knoldus › accessing-private-fields-and-methods-using-reflection-27caf3e5bdd4
Accessing private fields and methods using reflection | by Knoldus Inc. | Medium
April 26, 2020 - But as mentioned above, using reflection you can actually access the private methods of a class. And below is the snippet which makes this magic happen. val m = p.getClass.getDeclaredMethod(“greet”) m.setAccessible(true) m.invoke(p) If you run the above sample of code, then you will get the desired output. Hello Harshit ! Now let’s see how did all this happen even via reflection. So the first statement - p.getClass.getDeclaredMethod(“greet”) This statement, when executed, will return you the type java.lang.reflect.Method.
🌐
Codemia
codemia.io › knowledge-hub › path › change_private_static_final_field_using_java_reflection
Change private static final field using Java reflection
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
Top answer
1 of 16
1039

Assuming no SecurityManager is preventing you from doing this, you can use setAccessible to get around private and resetting the modifier to get rid of final, and actually modify a private static final field.

Here's an example:

import java.lang.reflect.*;

public class EverythingIsTrue {
   static void setFinalStatic(Field field, Object newValue) throws Exception {
      field.setAccessible(true);

      Field modifiersField = Field.class.getDeclaredField("modifiers");
      modifiersField.setAccessible(true);
      modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

      field.set(null, newValue);
   }
   public static void main(String args[]) throws Exception {      
      setFinalStatic(Boolean.class.getField("FALSE"), true);

      System.out.format("Everything is %s", false); // "Everything is true"
   }
}

Assuming no SecurityException is thrown, the above code prints "Everything is true".

What's actually done here is as follows:

  • The primitive boolean values true and false in main are autoboxed to reference type Boolean "constants" Boolean.TRUE and Boolean.FALSE
  • Reflection is used to change the public static final Boolean.FALSE to refer to the Boolean referred to by Boolean.TRUE
  • As a result, subsequently whenever a false is autoboxed to Boolean.FALSE, it refers to the same Boolean as the one refered to by Boolean.TRUE
  • Everything that was "false" now is "true"

Related questions

  • Using reflection to change static final File.separatorChar for unit testing
  • How to limit setAccessible to only “legitimate” uses?
    • Has examples of messing with Integer's cache, mutating a String, etc

Caveats

Extreme care should be taken whenever you do something like this. It may not work because a SecurityManager may be present, but even if it doesn't, depending on usage pattern, it may or may not work.

JLS 17.5.3 Subsequent Modification of Final Fields

In some cases, such as deserialization, the system will need to change the final fields of an object after construction. final fields can be changed via reflection and other implementation dependent means. The only pattern in which this has reasonable semantics is one in which an object is constructed and then the final fields of the object are updated. The object should not be made visible to other threads, nor should the final fields be read, until all updates to the final fields of the object are complete. Freezes of a final field occur both at the end of the constructor in which the final field is set, and immediately after each modification of a final field via reflection or other special mechanism.

Even then, there are a number of complications. If a final field is initialized to a compile-time constant in the field declaration, changes to the final field may not be observed, since uses of that final field are replaced at compile time with the compile-time constant.

Another problem is that the specification allows aggressive optimization of final fields. Within a thread, it is permissible to reorder reads of a final field with those modifications of a final field that do not take place in the constructor.

See also

  • JLS 15.28 Constant Expression
    • It's unlikely that this technique works with a primitive private static final boolean, because it's inlineable as a compile-time constant and thus the "new" value may not be observable

Appendix: On the bitwise manipulation

Essentially,

field.getModifiers() & ~Modifier.FINAL

turns off the bit corresponding to Modifier.FINAL from field.getModifiers(). & is the bitwise-and, and ~ is the bitwise-complement.

See also

  • Wikipedia/Bitwise operation

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?

public class A {
    private final String myVar = "Some Value";
}

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:

public class A {
    private final String myVar;

    private A() {
        myVar = "Some Value";
    }
}

if you are not the owner of the class... I feel you!

For more details about why this behavior read this?

2 of 16
69

If the value assigned to a static final boolean field is known at compile-time, it is a constant. Fields of primitive or String type can be compile-time constants. A constant will be inlined in any code that references the field. Since the field is not actually read at runtime, changing it then will have no effect.

The Java language specification says this:

If a field is a constant variable (§4.12.4), then deleting the keyword final or changing its value will not break compatibility with pre-existing binaries by causing them not to run, but they will not see any new value for the usage of the field unless they are recompiled. This is true even if the usage itself is not a compile-time constant expression (§15.28)

Here's an example:

class Flag {
  static final boolean FLAG = true;
}

class Checker {
  public static void main(String... argv) {
    System.out.println(Flag.FLAG);
  }
}

If you decompile Checker, you'll see that instead of referencing Flag.FLAG, the code simply pushes a value of 1 (true) onto the stack (instruction #3).

0:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3:   iconst_1
4:   invokevirtual   #3; //Method java/io/PrintStream.println:(Z)V
7:   return
🌐
Java2Blog
java2blog.com › home › core java › reflection › access private fields and methods using reflection in java
Access private fields and methods using reflection in java - Java2Blog
January 11, 2021 - In this post, we will see how to access private fields and methods using reflection in java. ... Access private method Can you access private fields and methods using reflection? Yes, you can. It is very easy as well. You just need to call .setAccessible(true) on field or method object which ...
🌐
Programming.Guide
programming.guide › java › accessing-private-fields-of-superclass-through-reflection.html
Java: Accessing private fields of superclass through reflection | Programming.Guide
In Java, difference between default, public, protected, and private ... Executing code in comments?! ... class C { private String privateField = "Hello World"; } class SubC extends C { } class Example { public static void main(String[] args) throws Exception { SubC obj = new SubC(); Field f = SubC.class.getSuperclass().getDeclaredField("privateField"); f.setAccessible(true); String str = (String) f.get(obj); System.out.println(str); // Hello World } }
🌐
CodingTechRoom
codingtechroom.com › question › set-private-field-spring-controller-reflection
How to Set a Private Field Using Reflection in a Spring Controller? - CodingTechRoom
Field field = YourClass.class.... when dealing with frameworks that require access to these fields. Java Reflection allows you to bypass encapsulation and modify private fields dynamically....
🌐
CodingTechRoom
codingtechroom.com › question › how-to-efficiently-set-private-field-using-reflection-java
How to Efficiently Set a Private Field Using Reflection in Java? - CodingTechRoom
import java.lang.reflect.Field; public class ReflectionExample { private String secret; public static void main(String[] args) throws Exception { ReflectionExample example = new ReflectionExample(); setPrivateField(example, "secret", "Hello Reflection"); System.out.println(example.getSecret()); // Output: Hello Reflection } public String getSecret() { return secret; } public static void setPrivateField(Object obj, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); field.set(obj, value); } }