Reflection
Inspecting Fields
Inspect class variables, read values, and write to fields using reflection.
Interview: Tests getField() vs getDeclaredField(), and accessing private fields using setAccessible(true).
The Reflection API allows dynamically querying class fields, reading values from active objects, and writing new values directly, bypassing encapsulation.
Core Idea
Reflection permits extracting field metadata and modifying instance values dynamically.
Why It Matters
Object-relational mapping (ORM) frameworks use this to read entity values and map them to SQL columns.
Interview Lens
Focuses on the difference between getFields() and getDeclaredFields(), and modifying final fields.
Method Differences
getFields(): Returns only public fields, including those inherited from parent classes.getDeclaredFields(): Returns all fields declared in the class (public, protected, package, and private), but excludes inherited fields.setAccessible(true): Instructs the JVM to bypass standard access checks, allowing writes to private fields.
Code Walkthrough
This program accesses and modifies a private field using reflection.
import java.lang.reflect.Field;class Account { private String id = "ACC_100"; }
public class FieldReflectionDemo { public static void main(String[] args) throws Exception { Account acc = new Account();
// Get private field by name Field idField = Account.class.getDeclaredField("id");
// Bypass private visibility check idField.setAccessible(true);
// Read value String value = (String) idField.get(acc); System.out.println("Original Private ID: " + value);
// Modify value idField.set(acc, "ACC_200"); System.out.println("Modified Private ID: " + idField.get(acc)); } }
Interview-Relevant Information
Q: Can reflection modify final fields?
Answer: Yes, but with limitations. You can modify a non-static final field by stripping its final modifier field-mask inside the Field metadata object using reflection. However, if the compiler inlined the final value (like a final String or primitive constant), subsequent reads will still show the old inlined constant, making modifications ineffective.
Quick Checklist
What is the difference between getFields() and getDeclaredFields()? How do you read a private field? If yes, you understand field reflection.
Use Cases
Dynamic mapping of configuration parameters directly to private fields.
Populating entity properties inside mock testing libraries.
Common Mistakes
Forgetting to call setAccessible(true) on private fields, throwing IllegalAccessException.
Searching for inherited fields using getDeclaredField(), which throws NoSuchFieldException (it only searches the local class).