Java Reflection: Get Field Value by String Name
Java reflection makes it possible to inspect and manipulate classes at runtime, and one of its most common uses is to get a field value by string name without knowing the field at compile time. This technique powers many frameworks, serialization libraries, mapping tools, and custom dependency injectors. Whether you are building a general-purpose object mapper or debugging an application where field names come from configuration or JSON, learning how to read a field dynamically using its name as a String is an essential skill. This guide walks through the concept, the exact steps, complete code examples, and the pitfalls you need to avoid The details matter here..
Counterintuitive, but true.
What Is Java Reflection?
Reflection is a feature of the Java language that lets a program examine or modify its own structure—classes, methods, constructors, and fields—during runtime. reflectpackage. lang.Now, it lives primarily in thejava. Instead of referring to a class or member directly by name in your source code, you reference it as an object and interact with it dynamically Worth keeping that in mind. That alone is useful..
This is fundamentally different from ordinary Java code. Even so, normally, to read a field, you write something like person. getName(). So with reflection, you write code that says, in effect, "find the field whose name equals the String I give you, then hand me its value. " That flexibility is powerful but comes with tradeoffs in performance and type safety.
Why Use Reflection to Read Fields?
There are several legitimate scenarios where reading a field value by its name string is the right approach:
- Generic frameworks that map data to objects without hardcoding every field.
- Configuration-driven logic where field names arrive from external sources like JSON, XML, or a database.
- Debugging and inspection tools that display the internal state of any object.
- Serialization libraries that must iterate over fields automatically.
The Core Classes You Need
Two classes from java.lang.reflect and `java.
Class<?>— represents the class whose field you want to read.Field— represents a single field and provides methods to read its value.
The Field class exposes the key method get(Object obj), which returns the field's value for a given object instance That alone is useful..
Step-by-Step: Get Field Value by String Name
Here is the reliable sequence you follow every time.
- Obtain the
Classobject for the target type usingMyClass.class,instance.getClass(), orClass.forName("com.example.MyClass"). - Locate the field with
getDeclaredField("fieldName")orgetField("fieldName"). - Open access with
field.setAccessible(true)when the field is not public. - Read the value with
field.get(instance), orfield.get(null)for static fields. - Handle exceptions such as
NoSuchFieldExceptionandIllegalAccessException.
A Complete Working Example
Consider a simple class:
public class Person {
private String name = "Ada Lovelace";
private int age = 36;
private static String species = "Human";
public String getName() {
return name;
}
}
Now read the name field dynamically using its string name:
import java.lang.reflect.Field;
public class ReflectionDemo {
public static void main(String[] args) {
try {
Person person = new Person();
// Step 1: locate the field by its name
Field field = person.getClass().getDeclaredField("name");
// Step 2: allow access to private members
field.setAccessible(true);
// Step 3: read the value
Object value = field.get(person);
System.In real terms, out. println("Value of 'name': " + value); // Ada Lovelace
} catch (NoSuchFieldException | IllegalAccessException e) {
e.
This is the canonical pattern for **getting a field value by string name** in Java, and it works even when the field is `private`.
## `getField` vs. `getDeclaredField`
Understanding the difference between these two methods prevents a lot of confusion:
- **`getField(name)`** returns only **public** fields, including those inherited from superclasses.
- **`getDeclaredField(name)`** returns **any** field—private, protected, or public—that is **declared directly** in the class, but it does **not** search parent classes.
If your target field is public and may be inherited, `getField` is convenient. If it is private or you need full control, `getDeclaredField` combined with `setAccessible(true)` is the standard choice.
## Reading Static Fields
For a static field, there is no instance, so you pass `null` to `get`:
```java
Field field = Person.class.getDeclaredField("species");
field.setAccessible(true);
Object value = field.get(null); // Human
Handling Fields in Superclasses
A common trap is that getDeclaredField only looks at the class you called it on. If the field lives in a parent class, you must walk up the inheritance chain yourself:
import java.lang.reflect.Field;
public class ReflectionUtils {
public static Field findField(Class> clazz, String fieldName)
throws NoSuchFieldException {
Class> current = clazz;
while (current !On top of that, = null && current ! = Object.class) {
try {
return current.Also, getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
current = current. getSuperclass(); // move up the hierarchy
}
}
throw new NoSuchFieldException(
"Field '" + fieldName + "' not found in " + clazz.
public static Object readField(Object target, String fieldName)
throws Exception {
Field field = findField(target.getClass(), fieldName);
field.setAccessible(true);
return field.
This helper reliably reads inherited fields, which `getDeclaredField` alone cannot do.
## Type-Specific Access and Casting
The generic `get` method returns an `Object`, so you cast or convert as needed:
```java
Field ageField
Field `ageField` illustrates the next logical step: once a `Field` object is obtained, you must invoke the appropriate type‑specific accessor. The generic `get(Object)` method returns `Object`, so you need to cast or convert the result to the expected Java type. For primitive wrapper types the JVM provides dedicated getters:
```java
Field ageField = ReflectionUtils.findField(Person.class, "age");
ageField.setAccessible(true);
int age = ageField.getInt(person); // int primitive
Integer ageObj = (Integer) ageField.get(person); // Integer wrapper
If the field holds a String, an int[], or a custom object, the same principle applies—use getString(), getIntArray(), getObject() respectively. When the declared type is a generic class (e.g.
ParameterizedType paramType = (ParameterizedType) ageField.getGenericType();
Class> elementType = paramType.getActualTypeArguments()[0];
Casting the result to the element type allows you to work with the collection safely:
List names = (List) ageField.get(person);
Caching for Performance
Repeated reflection on the same field can be expensive because each call traverses the inheritance chain and may invoke setAccessible(true). A common optimisation is to cache the Field objects after the first lookup:
private static final Map CACHE = new ConcurrentHashMap<>();
static Field getField(Class clazz, String name) throws NoSuchFieldException {
FieldKey key = new FieldKey(clazz, name);
return CACHE. In real terms, computeIfAbsent(key, k -> {
Class > current = clazz;
while (current != null) {
try {
return current.getDeclaredField(name);
} catch (NoSuchFieldException ignored) {
current = current.
Short version: it depends. Long version — keep reading.
The `FieldKey` class implements `equals` and `hashCode` based on the `Class` and the field name, ensuring correct map behaviour. With this cache in place, subsequent reads become virtually as fast as a regular field access.
### Dealing with Nulls and Access Control
When a field is declared `static final` or `private`, the JVM may enforce stricter access rules, especially under a security manager. In such environments, calling `setAccessible(true)` may throw a `SecurityException`. A defensive wrapper can catch this and fall back to a safe default:
```java
Object readField(Object target, String name) {
try {
Field field = ReflectionUtils.findField(target.getClass(), name);
field.setAccessible(true);
return field.get(target);
} catch (SecurityException se) {
System.err.println("Security restriction prevented access to " + name);
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
When Reflection Is Not the Best Fit
While reflection is powerful, it has drawbacks:
- Performance overhead – each access incurs a method‑call cost and may bypass JVM optimisations.
- Maintainability – code that depends on field names is fragile; refactoring a class can break it silently.
- Encapsulation violation – bypassing access modifiers can lead to unintended side effects and break future Java versions that tighten encapsulation.
In many cases, compile‑time alternatives (e.g.invokeMethodHandles) provide the same flexibility without the runtime penalties. , generics, annotations processed by an annotation processor, or usingjava.Here's the thing — lang. Still, reflection remains indispensable for frameworks, serialization libraries, and interactive tools where dynamic discovery is required Worth knowing..
Conclusion
Obtaining a field value by name in Java involves three core steps:
- Locate the field – use
getDeclaredField(or the helper that walks the superclass hierarchy) to retrieve the exactFieldobject, making it accessible withsetAccessible(true)if it is not public. - **Read the value