Course contentsShow
← Java
Lesson 2353 of 2,87045. Reflection APIFree lesson

Field.set: Writing Field Values

Learn how Field.set modifies a field's value on an object instance, including type checking and proper value assignment.

Field.set: Writing Field Values

You'll learn how to modify a field's value on an object instance reflectively using Field.set.

Writing to Fields Reflectively

After reading field values with Field.get, you often need to write new values back. The Field.set(Object obj, Object value) method lets you modify a field's value on a specific object instance (or the class itself for static fields).

How Field.set Works

The set method takes two arguments:

  1. Target object: The instance whose field you want to modify (or null for static fields)
  2. New value: The value to assign to the field
Field field = MyClass.class.getDeclaredField("count");
field.setAccessible(true); // If the field is private

MyClass instance = new MyClass();
field.set(instance, 42); // Sets instance.count = 42

Type Checking and Safety

Java enforces type safety even with reflection. The value you pass must be compatible with the field's declared type:

  • Primitive fields accept their wrapper types (autoboxing applies)
  • Reference fields require compatible types
  • Passing incompatible types throws IllegalArgumentException
Field nameField = Person.class.getDeclaredField("name");
nameField.set(person, "Alice"); // ✓ String matches String field

nameField.set(person, 123); // ✗ IllegalArgumentException: int cannot be String

Static Fields

For static fields, pass null as the target object:

Field staticField = MyClass.class.getDeclaredField("version");
staticField.setAccessible(true);
staticField.set(null, "2.0"); // Modifies static field

Key Takeaway: Field.set(obj, value) modifies a field's value reflectively, performing type checking and supporting both instance and static fields with proper access control.