Skip to content
AgileLogics
5 min read

Reflection & Annotations

Prerequisites: Design patterns in Java

Reflection lets code inspect and manipulate classes, methods, and fields at runtime — the mechanism frameworks like Spring and JUnit use to find and call your @Test or @Autowired-annotated code without you wiring it up by hand.

import java.lang.reflect.Method;

Class<?> clazz = "hello".getClass();
System.out.println(clazz.getName()); // java.lang.String

for (Method m : clazz.getDeclaredMethods()) {
    System.out.println(m.getName());
}

An annotation (@Override, @Test, or a custom @interface) attaches metadata to code that reflection (or the compiler itself) can read later:

@interface Important {}

@Important
void criticalTask() {}

Common mistakes

  • Using reflection for everyday application code — it's slower than direct calls and bypasses compile-time type checking. It's a tool for building frameworks and libraries, not typical business logic.