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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
