Field Objects: Representing Class Fields Reflectively
What You'll Learn
You'll learn how Field objects represent class fields in reflection and how to obtain them using Class methods.
Understanding Field Objects
A Field object is Java's reflective representation of a class field (instance variable or static variable). Just as Method objects represent methods, Field objects give you runtime access to a class's fields—their names, types, modifiers, and even their values in specific instances.
Think of a Field object as a mirror that reflects a particular variable defined in your class. Instead of accessing the variable directly by name in code, you hold a runtime handle to it that lets you inspect and manipulate it dynamically.
Obtaining Field Objects
The Class object provides methods to retrieve Field instances:
getField(String name)– Returns aFieldfor a public field (inherited or declared)getDeclaredField(String name)– Returns aFieldfor any field declared in this class, regardless of visibility (including private fields)
The distinction mirrors what you've seen with methods: getField respects inheritance and visibility rules, while getDeclaredField focuses on the exact class definition.
Class<?> clazz = MyClass.class;
// Get a public field (from this class or inherited)
Field publicField = clazz.getField("publicName");
// Get any field declared in this class, even private
Field privateField = clazz.getDeclaredField("privateBalance");
Once you have a Field object, you can inspect its properties (type, modifiers) or read/write its value in object instances—topics you'll explore next.
Key Takeaway:
Field objects represent class fields reflectively; obtain them with getField(name) for public fields or getDeclaredField(name) for any field declared in the class.