Lesson 35: Reflection API Basics

05 Aug 2026 1 min Swarnil Singhai

Reflection lets code inspect and manipulate classes, methods, and fields at runtime — the mechanism behind most Java frameworks.

Real-time example

A dependency-injection container reads a class's fields via reflection to figure out what dependencies to inject, without the class telling it directly.

class UserService {
    private String name = "default";
}
Field f = UserService.class.getDeclaredField("name");
f.setAccessible(true);
UserService svc = new UserService();
System.out.println(f.get(svc)); // "default"
f.set(svc, "injected-value");
System.out.println(f.get(svc)); // "injected-value"

What's happening

setAccessible(true) bypasses the private modifier — powerful, but it breaks encapsulation, so frameworks use it sparingly and deliberately.

Reflection is slow relative to direct calls — frameworks cache reflective lookups instead of repeating them per request.

Advertisement