What is the Java Reflection API?
The Java Reflection API, in the `java.lang.reflect` package, enables a program to examine and modify its own structure and behavior at runtime. It allows code to inspect class metadata, invoke methods, access fields, and instantiate objects using symbolic names rather than compile-time references.
The entry point is `Class<?>`, obtained via `obj.getClass()`, `MyClass.class`, or `Class.forName("com.example.MyClass")`. From a `Class` object you can retrieve `Method`, `Field`, `Constructor`, and `Annotation` objects, then invoke methods or get/set fields even if they are private (after calling `setAccessible(true)`, subject to module and security constraints).
Common use cases: dependency injection frameworks (Spring reads annotations and injects beans), ORM tools (Hibernate maps fields to columns), serialization libraries (Jackson introspects field names), testing frameworks (JUnit discovers test methods by annotation), plugin systems (loading classes by name at runtime).
Reflection is powerful but carries real costs: 1. Performance: reflective invocation bypasses JVM optimizations (inlining, JIT hotspot compilation). Method.invoke() is measurably slower than direct calls, though `MethodHandle` (java.lang.invoke) and `invokedynamic` provide more performant alternatives. 2. Type safety: errors that would be caught at compile time (wrong argument types, missing methods) become runtime exceptions (`IllegalArgumentException`, `NoSuchMethodException`). 3. Encapsulation violation: `setAccessible(true)` overrides visibility modifiers, which was unrestricted before Java 9. Java 9+ module system (`--add-opens`) enforces access boundaries, limiting deep reflection on JDK internals and third-party modules. 4. Security: in security-managed environments, reflective access requires permissions that may not be granted.
For interviews at senior level, know that `MethodHandle` is the modern, performance-friendly alternative for dynamic dispatch, and that the module system materially changed what reflection can access.
Explains what reflection does, names at least three real-world use cases, and mentions performance and type-safety costs.
Also covers the Java 9 module system impact on setAccessible(), MethodHandle as a modern alternative, and can explain the specific exception hierarchy for reflective failures.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment