Java / Java 21 Interview Questions
How does Java Reflection work and what are its performance implications?
Reflection allows programs to inspect and manipulate classes, methods, fields, constructors, and annotations at runtime — without knowing them at compile time. It powers frameworks like Spring (dependency injection), Hibernate (ORM), JUnit (test discovery), and Jackson (JSON serialisation).
import java.lang.reflect.*;
// Inspect a class at runtime
Class> clazz = Class.forName("com.example.User");
// or: User.class or user.getClass()
// Fields
for (Field f : clazz.getDeclaredFields()) {
f.setAccessible(true); // bypass private access
System.out.println(f.getName() + " : " + f.getType().getSimpleName());
}
// Methods
Method method = clazz.getDeclaredMethod("setName", String.class);
method.setAccessible(true);
method.invoke(userInstance, "Alice"); // calls userInstance.setName("Alice")
// Constructor — create an instance dynamically
Constructor> ctor = clazz.getDeclaredConstructor(String.class, int.class);
ctor.setAccessible(true);
Object user = ctor.newInstance("Alice", 30);
// Annotations — reading custom metadata
@Retention(RetentionPolicy.RUNTIME) // must be RUNTIME to read via reflection
@Target(ElementType.METHOD)
@interface Timed { String value() default ""; }
@Timed("fetchUser")
void fetchUser() { /* ... */ }
Method m = SomeClass.class.getMethod("fetchUser");
if (m.isAnnotationPresent(Timed.class)) {
Timed t = m.getAnnotation(Timed.class);
System.out.println("Timer label: " + t.value());
}Performance implications: Reflection bypasses JIT optimisations (inlining, escape analysis) and incurs overhead from security checks, type conversions, and dynamic dispatch. setAccessible(true) in Java 9+ requires the module to be opened. Java 21 provides MethodHandles as a faster alternative for repeated reflective access — they can be specialised and inlined by the JIT after a warm-up period.
More Related questions...