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

Getting a Specific Field by Name

Learn getField() and getDeclaredField() to retrieve a specific field for reading or modifying its value.

Getting a Specific Field by Name

You'll learn how to retrieve a single field directly by name, allowing precise access for reading or modifying its value.

So far, you've learned to retrieve all fields at once using getFields() or getDeclaredFields(). But when you already know the exact field name you need, Java's Reflection API provides targeted methods to fetch just that one field: getField() and getDeclaredField().

The Core Idea

Think of it like looking up a specific entry in a dictionary. Instead of flipping through all pages, you go directly to the word you need. Similarly, these methods let you retrieve a specific Field object by name without iterating through arrays.

getField(String name)

This method retrieves a public field with the specified name, including inherited public fields from superclasses and interfaces:

Class<?> clazz = MyClass.class;
Field publicField = clazz.getField("publicFieldName");

If the field doesn't exist or isn't public, it throws NoSuchFieldException.

getDeclaredField(String name)

This method retrieves any field declared in the specific class itself—including private, protected, and package-private fields—but does not include inherited fields:

Class<?> clazz = MyClass.class;
Field privateField = clazz.getDeclaredField("privateFieldName");

Also throws NoSuchFieldException if the field isn't declared in this class.

When to Use Which

  • Use getField() when accessing public API fields that might be inherited
  • Use getDeclaredField() when you need direct access to fields defined in a specific class, regardless of visibility

Once you have the Field object, you can read its value, modify it (if accessible), or work with its metadata.

Key Takeaway: Use getField() to retrieve public fields by name (including inherited ones), and getDeclaredField() to access any field declared directly in a class, enabling precise reflection operations on specific fields.