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

Field.get: Reading Field Values

Understand how Field.get retrieves a field's value from an object instance, including handling static fields and required type casting.

Field.get: Reading Field Values

You'll learn how to retrieve the actual value stored in a field using reflection, even when the field is private or static.

What Field.get Does

Once you've obtained a Field object (using getField() or getDeclaredField()), you can read the current value of that field from any instance using the get() method. Think of Field as a "universal key" that lets you peek inside an object's storage compartments—even the locked ones.

Basic Syntax

Field field = obj.getClass().getDeclaredField("fieldName");
Object value = field.get(obj);

The get() method takes the target object as its argument and returns the field's value as an Object. For instance fields, pass the specific object instance. For static fields, you can pass null since static fields belong to the class itself, not any particular instance.

Type Casting

Because get() returns Object, you'll need to cast the result to the appropriate type:

Field nameField = person.getClass().getDeclaredField("name");
String name = (String) nameField.get(person);

Field ageField = person.getClass().getDeclaredField("age");
int age = (int) nameField.get(person); // autoboxing handles Integer → int

Reading Static Fields

For static fields, pass null as the object argument:

Field countField = MyClass.class.getDeclaredField("instanceCount");
int count = (int) countField.get(null); // static field

Access Control

If the field is private, you must call field.setAccessible(true) first, or you'll get an IllegalAccessException.

Key Takeaway: Field.get(obj) retrieves a field's value from an object instance (or null for static fields), returning it as Object that must be cast to the correct type.