Skip to content
Reflection and Annotations
step 1/7

Reading — step 1 of 7

Learn

~1 min readReflection and JVM

Reflection lets code inspect and manipulate types at runtime. The classic use: serialization, dependency injection, ORM mapping.

Class<?> cls = User.class;
// Or: Class<?> cls = obj.getClass();
// Or: Class<?> cls = Class.forName("com.example.User");

// Inspect:
cls.getName();                     // "com.example.User"
cls.getDeclaredFields();           // Field[] — all fields
cls.getDeclaredMethods();          // Method[] — all methods
cls.getInterfaces();
cls.getSuperclass();

// Construct:
User u = (User) cls.getConstructor(String.class).newInstance("Ada");

// Read/write fields (even private):
Field f = cls.getDeclaredField("name");
f.setAccessible(true);             // bypass private
String name = (String) f.get(u);
f.set(u, "Linus");

// Invoke methods:
Method m = cls.getMethod("greet", String.class);
Object result = m.invoke(u, "hello");

Annotations are metadata, often inspected via reflection:

@Retention(RetentionPolicy.RUNTIME)    // available at runtime
@Target(ElementType.METHOD)
public @interface Cached {
    int ttl() default 60;
}

class Service {
    @Cached(ttl = 300)
    public String fetchData() { ... }
}

// Read at runtime:
Method m = Service.class.getMethod("fetchData");
Cached annot = m.getAnnotation(Cached.class);
if (annot != null) {
    int ttl = annot.ttl();         // 300
}

Use cases:

  • JSON libraries (Jackson, Gson) — read fields by name
  • Spring — @Autowired, @Component discovered via reflection
  • JUnit — @Test methods detected and invoked
  • ORMs (Hibernate) — @Entity, @Column map to DB

Caveats:

  • 10-100x slower than direct calls
  • Bypasses static type checks
  • setAccessible(true) breaks encapsulation
  • Compile-time tools (annotation processors) are usually preferred when applicable

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…