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
- Defining Annotations: Elements and Defaults
- Retention Policies and Target Types
- Runtime Annotation Processing
- Compile-Time Annotation Processors