0Pricing
Java Academy · Lesson

Runtime Annotation Processing

Read annotations at runtime using reflection to implement validation, routing, or injection logic.

Reading Class-Level Annotations

Retrieve annotations on a class using Class.getAnnotation() (single) or getAnnotations() (all). Returns null if the annotation is absent.

@Service
@RequestMapping("/api")
public class UserController {}

RequestMapping rm = UserController.class.getAnnotation(RequestMapping.class);
if (rm != null) System.out.println(Arrays.toString(rm.value())); // ["/api"]

Reading Method Annotations

Get method annotations via method.getAnnotation(). Iterate getDeclaredMethods() to scan all methods in a class.

for (Method m : UserController.class.getDeclaredMethods()) {
    GetMapping gm = m.getAnnotation(GetMapping.class);
    if (gm != null) System.out.println(m.getName() + " -> " + Arrays.toString(gm.value()));
}

All lessons in this course

  1. Defining Annotations: Elements and Defaults
  2. Retention Policies and Target Types
  3. Runtime Annotation Processing
  4. Compile-Time Annotation Processors
← Back to Java Academy