Reflection
Reflection Basics
Understand the Java Reflection API, its capabilities, and security/performance implications.
Interview: Tests fundamental principles: how reflection bypasses access modifiers, performance overhead, and security manager restrictions.
Reflection is a Java feature that allows an executing program to inspect, modify, and instantiate classes, methods, fields, and constructors at runtime, bypassing compile-time type checking.
Core Idea
Reflection inspects class metadata dynamically, allowing runtime access to private class members.
Why It Matters
Power frameworks (like JUnit, Spring, Jackson) require reflection to load beans and execute tests dynamically.
Interview Lens
Expect questions on why reflection is slow (bypasses JIT compilation optimizations) and how it affects security.
Reflection Capabilities and Trade-offs
- Access Bypassing: You can call
setAccessible(true)on fields/methods to read or executeprivateclass members. - Performance Overhead: Because types are resolved dynamically at runtime, JVM JIT compiler optimizations (like method inlining) are bypassed, making reflection slow.
- Type Safety Risks: Bypassing compiler checks increases the risk of runtime exceptions (like
NoSuchMethodException).
Code Walkthrough
This program demonstrates how reflection can inspect class names dynamically at runtime.
public class ReflectionBasicsDemo { public static void main(String[] args) throws ClassNotFoundException { // Retrieve class metadata dynamically Class clazz = Class.forName("java.lang.String");
System.out.println("Class Name: " + clazz.getName()); System.out.println("Is Interface? " + clazz.isInterface()); } }
Interview-Relevant Information
Q: Why should reflection be avoided in hot code paths?
Answer: Reflection requires lookup operations by name, access permission checks, and parameter boxing/unboxing. Since these operations happen at runtime, the JIT compiler cannot optimize them, resulting in execution times that can be orders of magnitude slower than direct method invocation.
Quick Checklist
How do you bypass private access modifiers using reflection? Why is reflection slow? If yes, you understand reflection basics.
Use Cases
Building generic test runner frameworks (like JUnit) that find and run methods labeled with @Test.
Developing serialization libraries (like Jackson) to convert JSON keys to private fields.
Common Mistakes
Using reflection in performance-critical code paths (like inner loops).
Assuming reflection works on obfuscated code (obfuscators rename fields and methods, breaking string-based lookups).