Getting Fields with getFields()
You'll learn how to retrieve all public fields from a class and its ancestors using reflection's getFields() method.
What Are Fields in Reflection?
When working with the Class object, you often need to discover what fields (variables) a class exposes. The getFields() method returns an array of Field objects representing all public fields, including those inherited from superclasses and interfaces.
Think of it like asking for a directory of all publicly visible storage locations in an object's family tree—not just the class itself, but everything it inherited that's marked public.
How getFields() Works
Call getFields() on a Class object, and you'll receive a Field[] array. Each Field object represents one public field and can tell you its name, type, and modifiers.
Class<?> clazz = String.class;
Field[] publicFields = clazz.getFields();
for (Field field : publicFields) {
System.out.println("Field name: " + field.getName());
System.out.println("Field type: " + field.getType());
}
Public and Inherited
The key distinction: getFields() returns only public fields, but it searches the entire inheritance hierarchy. If a superclass has a public field, it will appear in this array.
class Parent {
public String parentField = "visible";
private String secretField = "hidden";
}
class Child extends Parent {
public int childField = 42;
}
Class<?> childClass = Child.class;
Field[] fields = childClass.getFields();
// Returns: parentField and childField (not secretField)
When to Use It
Use getFields() when you need to inspect or manipulate all publicly accessible fields, perhaps for serialization, data binding, or framework introspection tasks.
Key Takeaway: getFields() retrieves all public fields from a class and its ancestors as a Field[] array, giving you reflection-based access to publicly visible data members across the inheritance chain.