Sub topic 5
Reading and writing fields
This chapter assumes you can already get a Class object and list its members with getDeclaredFields(). If not, review the two chapters before this one. Here you will read and change field values on live objects, handle the exceptions that can occur, and avoid the usual traps with static, final, and inherited fields.
The Field object
A java.lang.reflect.Field describes one field. It is not a value. It is a handle that can read or write that field on any object of the right class, so you can reuse one Field for many instances.
You get a Field in two ways:
getField(name)finds a field that ispublic, including public fields inherited from superclasses and interfaces.getDeclaredField(name)finds a field declared by that exact class, whatever its access level. It does not search superclasses.
Both throw the checked NoSuchFieldException if nothing matches.
Reading and writing values
The main methods are get(Object target) and set(Object target, Object value). Both use Object, so primitives are boxed and unboxed for you. Typed variants such as getInt, setInt, getBoolean, and setDouble skip the boxing and check the type more strictly.
import java.lang.reflect.Field;
class Account {
public String owner = "Ada";
private int balance = 100;
static int created = 7;
}
public class FieldReadWrite {
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);
balance.setInt(acc, balance.getInt(acc) + 50);
System.out.println(balance.get(acc));
Field created = Account.class.getDeclaredField("created");
System.out.println(created.get(null));
created.set(null, 8);
System.out.println(Account.created);
}
}This prints Ada, 150, 7, and 8. Three points to note:
balanceis private, so the code callssetAccessible(true)before using it. Without that call,getwould throwIllegalAccessException. The next chapter covers whatsetAccessiblecan and cannot do under the module system.createdis static, so the target argument is ignored and you passnull.owneris public and in the same package, so nosetAccessiblecall is needed.
Which accessor to use
| Method | Behavior |
|---|---|
| `get` / `set` | Boxes and unboxes primitives. `set` also widens, so an `Integer` can be stored in a `long` field. |
| `getInt` / `setInt` and the other typed pairs | Work with raw primitives. `getLong` on an `int` field works because it widens. `getInt` on a `long` field throws. |
| `getType()` | Returns the declared type as a `Class`. |
| `getModifiers()` | Returns the modifier bits. Test them with `Modifier.isStatic` and `Modifier.isFinal`. |
What goes wrong
Field access has four common failure modes. The following program triggers each of them.
import java.lang.reflect.Field;
class Server {
final int port;
static final int MAX = 10;
long uptime = 5L;
Server(int port) {
this.port = port;
}
}
public class FieldErrors {
public static void main(String[] args) throws Exception {
Server s = new Server(8080);
Field uptime = Server.class.getDeclaredField("uptime");
try {
uptime.set(s, "soon");
} catch (IllegalArgumentException e) {
System.out.println("wrong type");
}
try {
uptime.get(null);
} catch (NullPointerException e) {
System.out.println("null target for instance field");
}
uptime.set(s, 9);
System.out.println(uptime.getLong(s));
Field port = Server.class.getDeclaredField("port");
try {
port.set(s, 1);
} catch (IllegalAccessException e) {
System.out.println("final field blocked");
}
port.setAccessible(true);
port.set(s, 9090);
System.out.println(port.getInt(s));
Field max = Server.class.getDeclaredField("MAX");
max.setAccessible(true);
try {
max.set(null, 11);
} catch (IllegalAccessException e) {
System.out.println("static final blocked");
}
}
}The output is:
wrong type
null target for instance field
9
final field blocked
9090
static final blockedThe four failures:
IllegalArgumentException. The value cannot be converted to the field type. AStringcannot go into alongfield. AnIntegercan, because it widens. ALongcannot go into anintfield, because that would narrow.NullPointerException. You passed anulltarget for an instance field. Only static fields acceptnull.IllegalAccessExceptionon a final instance field. It is thrown untilsetAccessible(true)succeeds. After that, the write works on ordinary classes. It still fails on records and hidden classes.IllegalAccessExceptionon a static final field. This fails even aftersetAccessible(true). The JVM may have already inlined the value.
IllegalAccessException and NoSuchFieldException are checked exceptions, so your method must declare or catch them. The other two are unchecked.
Fields in a class hierarchy
getDeclaredField looks only at the class you call it on. If a private field is declared in a superclass, Child.class.getDeclaredField("x") throws NoSuchFieldException. To find such a field, walk up the chain:
import java.lang.reflect.Field;
class Base {
private String id = "base-1";
}
class Child extends Base {
private String label = "child";
}
public class Hierarchy {
static Field findField(Class<?> type, String name) throws NoSuchFieldException {
for (Class<?> c = type; c != null; c = c.getSuperclass()) {
try {
return c.getDeclaredField(name);
} catch (NoSuchFieldException ignored) {
// keep looking in the superclass
}
}
throw new NoSuchFieldException(name);
}
public static void main(String[] args) throws Exception {
Child child = new Child();
Field id = findField(Child.class, "id");
id.setAccessible(true);
System.out.println(id.get(child));
}
}This prints base-1. If a subclass declares a field with the same name as a superclass field (field hiding), the loop returns the subclass's field first. The superclass field is still there, and you can reach it by starting the loop at the superclass.
The same loop is the usual way to collect all fields of an object. Call getDeclaredFields() at each level, and skip synthetic fields such as this$0, which the compiler adds to inner classes (check isSynthetic()).
Practical habits
- Cache
Fieldobjects. Looking up a field by name costs more than reading it, and aFieldcan be reused across instances.Class.getDeclaredFieldalso returns a fresh copy each time, so callsetAccessible(true)on the copy you keep. - Check the type with
getType()before callingsetwhen the value comes from outside, such as a configuration file. Convert the value yourself and do not rely on the exception. - Keep
setAccessible(true)calls in one helper. It makes the code easier to audit and to adapt when modules restrict access. - Prefer the typed getters and setters for primitive fields in hot paths, since they avoid boxing.
Reading and writing fields is the basis for the validator you will build later in this tutorial. It finds annotated fields, reads their values, and reports the ones that fail a rule.
Exercise
A class Point has a private int field x. You call Point.class.getDeclaredField("x"), then field.setInt(p, 5) without calling setAccessible(true), from a different class in a different package. What happens, and what single change fixes it?
Show answer
setInt throws IllegalAccessException, because the field is private and the caller is not allowed to access it. Calling field.setAccessible(true) before setInt fixes it, provided the module system allows it (the package is in an unnamed module, or the module opens the package to the caller).
Exercise
Class Dog extends Animal, and Animal declares a private String name. Dog.class.getDeclaredField("name") throws NoSuchFieldException. Why does it fail, and how do you find the field?
Show answer
getDeclaredField only searches the class it is called on, and name is declared in Animal. Call Animal.class.getDeclaredField("name"), or loop over getSuperclass() starting from Dog.class until a class declares the field. Then call setAccessible(true) before reading or writing it.
Exercise
You have a long field named count. Which of these calls succeed: field.set(obj, 5), field.set(obj, 5L), field.setInt(obj, 5), field.getInt(obj)?
Show answer
The first three succeed. set(obj, 5) boxes to an Integer and widens to long, set(obj, 5L) matches exactly, and setInt widens the int to long. field.getInt(obj) throws IllegalArgumentException, because reading a long as an int would narrow it. Use getLong instead.