Sub topic 5
Reading and writing fields
This chapter assumes you can already get a Class object and list a type's members with getDeclaredFields(). Here you will read and change field values on a live object.
Finding the Field
A Field object describes one field. You get it from a Class in two ways:
getField(name)finds a public field, including inherited ones.getDeclaredField(name)finds any field declared in that class, whatever its access level. It does not search superclasses.
Both throw NoSuchFieldException if no field matches. To reach a private field in a superclass, call getDeclaredField on the superclass itself, or walk up with getSuperclass().
Reading and writing values
Once you hold a Field, you pass the target object to its methods:
field.get(obj)returns the value as anObject. Primitives are boxed.field.set(obj, value)assigns a new value. Primitives are unboxed.- Typed variants such as
getInt,setInt,getBooleanandsetDoubleavoid boxing.
For a static field, the object argument is ignored, so pass null.
import java.lang.reflect.Field;
class Account {
public String owner = "Ada";
private int balance = 100;
static int count = 0;
}
public class FieldDemo {
public static void main(String[] args) throws Exception {
Account acc = new Account();
Field owner = Account.class.getField("owner");
System.out.println(owner.get(acc));
Field balance = Account.class.getDeclaredField("balance");
balance.setAccessible(true);
int before = balance.getInt(acc);
balance.setInt(acc, before + 50);
System.out.println(balance.get(acc));
Field count = Account.class.getDeclaredField("count");
count.set(null, 7);
System.out.println(Account.count);
}
}The program prints Ada, 150 and 7.
The balance field is private, so the code calls setAccessible(true) first. Without it, get throws IllegalAccessException. The next chapter section covers what setAccessible can and cannot do under the module system.
The flow of a field access
Common errors
| Exception | Typical cause |
|---|---|
| `NoSuchFieldException` | Wrong name, or `getField` used on a non-public field, or the field lives in a superclass and you used `getDeclaredField` |
| `IllegalAccessException` | Non-public field without `setAccessible(true)`, or a write to a `final` field |
| `IllegalArgumentException` | The object is not an instance of the field's class, or the value has the wrong type |
| `NullPointerException` | `null` passed as the target for an instance field |
Final fields
A static final field cannot be set, even after setAccessible(true). An instance final field can be written once setAccessible(true) has succeeded, but you should avoid it. The compiler and JIT may have inlined the old value, so other code can keep seeing it.
Exercise
A class Base has a private field id, and Child extends Base. Why does Child.class.getDeclaredField("id") throw NoSuchFieldException, and how do you fix it?
Show answer
getDeclaredField only looks at fields declared in the class it is called on, and id is declared in Base. Call Base.class.getDeclaredField("id"), or loop through getSuperclass() until the field is found. Then call setAccessible(true) before get or set.