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

Getting Declared Fields: Class-Specific Fields Only

Use getDeclaredFields() to access all fields declared in a class, including private fields.

Getting Declared Fields: Class-Specific Fields Only

What you'll learn: How to use getDeclaredFields() to access all fields defined directly in a class, including private ones, without inheriting from parent classes.

Understanding getDeclaredFields()

In the previous lesson, you learned about getFields(), which returns only public fields from a class and its entire inheritance hierarchy. But what if you need to see all fields declared specifically in one class, regardless of their access level?

That's where getDeclaredFields() comes in. This method returns an array of Field objects representing every field declared directly in the class—public, protected, package-private, and private—but not inherited fields.

The Key Difference

Think of it like examining a family tree:

  • getFields() is like asking "Who are all the public members in my entire family lineage?"
  • getDeclaredFields() is like asking "Who are all the members born directly into this specific generation, regardless of visibility?"

Using getDeclaredFields()

import java.lang.reflect.Field;

class BankAccount {
    public String accountNumber;
    private double balance;
    protected String owner;
    int transactionCount; // package-private
}

public class FieldInspector {
    public static void main(String[] args) {
        Class<?> clazz = BankAccount.class;
        
        Field[] declaredFields = clazz.getDeclaredFields();
        
        System.out.println("Declared fields in BankAccount:");
        for (Field field : declaredFields) {
            System.out.println(field.getName() + " - " + field.getType().getSimpleName());
        }
    }
}

This outputs all four fields, including the private balance field—something getFields() would miss.

Key Takeaway: Use getDeclaredFields() when you need complete visibility into all fields defined in a specific class, including private members, without traversing the inheritance hierarchy.