Reflection API
TL;DR
- The Reflection API (
java.lang.reflect) allows a Java program to inspect and manipulate itself at runtime. - You can discover the methods, fields, and constructors of any class dynamically, even if you didn’t know the class existed at compile time.
- It is the core technology behind modern Java frameworks like Spring, Hibernate, and JUnit.
Concept
Normally, Java is a statically-typed, strongly-bound language. If you want to call user.getName(), the compiler verifies that the User class has a getName() method. If it doesn’t, it refuses to compile.
Reflection allows you to write code that says: “I have an unknown object. Please give me a list of all its methods. Does it have one called ‘getName’? If so, invoke it.”
This bypasses static compiler checks and executes dynamically at runtime.
It also allows you to bypass access modifiers, giving you the ability to read and modify private variables from outside the class!
Examples
import java.lang.reflect.Method;
class SecretBox {
private void open() {
System.out.println("The secret box is open!");
}
}
public class ReflectionApiDemo {
public static void main(String[] args) {
try {
SecretBox box = new SecretBox();
// Standard Java: box.open(); // ERROR! open() has private access.
// Reflection:
Class<?> clazz = box.getClass();
// 1. Find the private method
Method openMethod = clazz.getDeclaredMethod("open");
// 2. Suppress Java access checking (the magic bypass)
openMethod.setAccessible(true);
// 3. Invoke the method on our specific 'box' instance
openMethod.invoke(box);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Interview Questions
Q: Why shouldn’t you use Reflection for everyday programming tasks?
A: 1. Performance: Reflection operations are much slower than direct code because the JVM cannot optimize them using JIT (Just-In-Time) compilation. Every call requires dynamic resolution.
2. Security & Stability: It breaks encapsulation. You can accidentally break the internal invariants of a class by modifying private fields, leading to obscure bugs.
3. Refactoring: If you rename a method from open() to unlock(), normal Java code will automatically update in your IDE. But Reflection code (which relies on the string "open") will silently break and only crash at runtime.
Q: How does Spring Boot use Reflection?
A: When you annotate a class with @RestController and add an @Autowired private field, Spring uses Reflection during application startup. It scans your classpath, finds the class, dynamically creates an instance of it, finds the private field, calls setAccessible(true), and forcefully injects the required dependency directly into the private variable.