library
advancedReflection API
Inspect and modify class structure, fields, methods, and constructors at runtime — and know the costs.
The Reflection API (java.lang.reflect) lets you examine and manipulate classes, methods, fields, and constructors at runtime. It's the backbone of frameworks like Spring, Hibernate, JUnit, and Jackson.
Reflection = X-ray vision. You can see inside any object (private fields), operate on it (invoke methods), and create copies (newInstance). But it's slower than just using the door (normal method calls).
Key Concepts
1
Core classes:
- Class<T>: represents a class. Get via obj.getClass(), String.class, Class.forName("...").
- Method: represents a method. Invoke with method.invoke(obj, args).
- Field: represents a field. Read/write with field.get(obj), field.set(obj, value).
- Constructor<T>: represents a constructor. Create instances with constructor.newInstance(args).
2
Access control bypass: setAccessible(true) lets you access private members. This bypasses compile-time checks but NOT module system checks (JPMS exports/opens).
3
Performance cost: reflection is 5-50x slower than direct calls because:
- No compile-time optimization or inlining
- Security checks on every call
- Boxing of primitive arguments/returns
- Dynamic method resolution
4
Use cases: dependency injection (Spring), ORM mapping (Hibernate), serialization (Jackson), test frameworks (JUnit), annotation processing.
5
Alternatives: MethodHandle (faster, introduced in Java 7) and VarHandle (Java 9) offer better performance for repeated access. Code generation (ByteBuddy, ASM) eliminates reflection entirely in hot paths.