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.
🌐
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 ·
🌐
W3Schools Blog
w3schools.blog › get-set-private-field-value-in-java
Java reflection get set private field value – W3schools
package com.w3spoint; import java.lang.reflect.Field; public class ReflectionTest { public static void main(String args[]){ try { TestClass testClass = new TestClass(); Class c=Class.forName("com.w3spoint.TestClass"); Field field = c.getDeclaredField("testField"); field.setAccessible(true); System.out.println(field.get(testClass)); field.setInt(testClass, 50); System.out.println(field.get(testClass)); } catch (Exception e) { e.printStackTrace(); } } }
🌐
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 - @Test public void whenGetBooleanFields_thenSuccess() throws Exception { Person person = new Person(); Field activeField = person.getClass().getDeclaredField("active"); activeField.setAccessible(true); boolean active = activeField.getBoolean(person); Assertions.assertTrue(active); } We can access the private fields that are objects by using the Field#get method. It is to note that the generic get method returns an Object, so we’ll need to cast it to the target type to make use of the value:
🌐
CodingTechRoom
codingtechroom.com › tutorial › java-set-private-field-value-java
How to Set Private Field Value in Java: A Comprehensive Guide - CodingTechRoom
By following this tutorial, you can confidently set private field values in Java using reflection, which opens up powerful capabilities when working with object-oriented programming.
🌐
Programiz
programiz.com › java-programming › examples › access-private-members
Java Program to Access private members of a class
the getter methods getAge() and getName() returns the value of private variables · import java.lang.reflect.*; class Test { // private variables private String name; // private method private void display() { System.out.println("The name is " + name); } } class Main { public static void main(String[] args) { try { // create an object of Test Test test = new Test(); // create an object of the class named Class Class obj = test.getClass(); // access the private variable Field field = obj.getDeclaredField("name"); // make private field accessible field.setAccessible(true); // set value of field
Find elsewhere
🌐
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
🌐
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.
🌐
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 this article, we will see a simple example of accessing a private field using reflection and invoking a private method using reflection in Java. In order to access a private field using reflection, you need to know the name of the field than by calling getDeclaredFields(String name) you will get a java.lang.reflect.Field instance representing that field.
Top answer
1 of 10
9

You are not missing anything. What you do depends entirely on your situation. However, consider this:

It is very common to do parameter validation in a setter. For example, let's say I have a class with field that can hold a value 0 through 10 (the "throws" is unnecessary for the exception type below but I include it for clarity):

public class Example {
    private int value; 
    public Example () {
    }
    public final int getValue () {
        return value;
    } 
    public final void setValue (int value) throws IllegalArgumentException { 
        if (value < 0 || value > 10)
            throw new IllegalArgumentException("Value is out of range.");
    }
}

Here, setValue() validates 'value' to make sure it sticks to the rules. We have an invariant that states "an Example will not exist with an out of range value". Now let's say we want to make a constructor that takes a value. You might do this:

public class Example {
    ...
    public Example (int value) {
        this.value = value;
    }
    ...
}

As you can see, there is a problem. The statement new Example(11) would succeed, and now an Example exists that breaks our rules. However, if we use the setter in the constructor, we can conveniently add all parameter validation to the constructor as well:

public class Example {
    ...
    public Example (int value) throws IllegalArgumentException {
        setValue(value); // throws if out of range
    }
    ...
}

So there are many benefits to this.

Now, there are still cases when you might want to assign values directly. For one, maybe you don't have setters available (although I would argue that creating private or package private setters is still desirable, for the reasons mentioned above, for reflection/bean support if necessary, and for ease of validation in more complex code).

Another reason might be that perhaps you have a constructor that knows, somehow, ahead of time that valid values will be assigned, and therefore doesn't need validation and can assign variables directly. This is usually not a compelling reason to skip using setters though.

However, all-in-all, it's generally a good idea to use the setters everywhere when possible, it will usually lead to cleaner and clearer code that is easier to maintain as complexity increases.

Most of the examples you see where people set variables directly are just people being "lazy" - which is perfectly acceptable if the situation warrants it (perhaps you're writing a quick test program or application and don't want to implement a bunch of setters, for example). There's nothing wrong with that as long as you keep the big picture in mind and only be "lazy" when it's appropriate.

Something I'd like to add based on some of the other answers here: If you override a setter in a subclass, and the data you are setting breaks invariants that the base class assumes, then either the relevant setters should be made final or the base class should not make those assumptions. If overriding setters breaks base class invariants then there is a bigger issue at hand.

You'll notice the getter/setter is final in the above example. This is because our rule is that "any Example must have a value from 0 to 10". This rule therefore extends to subclasses. If we did not have that rule and if an Example could take on any value, then we would not need a final setter and could allow subclasses to override.

Hope that helps.

2 of 10
3

Sometimes when you would want make the class immutable, it is just one of the things you need to do. And don't have setter methods at all in that case.

🌐
DigitalOcean
digitalocean.com › community › tutorials › java-reflection-example-tutorial
Java Reflection Example Tutorial | DigitalOcean
August 3, 2022 - If the field is final, the set() methods throw java.lang.IllegalAccessException. We know that private fields and methods can’t be accessible outside of the class but using reflection we can get/set the private field value by turning off the java access check for field modifiers.
🌐
Coderanch
coderanch.com › t › 473481 › java › Private-variables-set
Private variables and get/set (Beginning Java forum at Coderanch)
December 3, 2009 - swapnl patil wrote: public : Accessible ... including subclasses, in the same package as its class (package accessibility). private : Only accessible in its own class and not anywhere else. so you cant access the private varibale . let me know if you any quires ....
🌐
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); This code example will print out the text "fieldValue = The Private Value", which is the value of the private field privateString of the PrivateObject instance created at the beginning of the code sample.