How would you read custom annotations at runtime using reflection to implement annotation-driven behavior, such as a simple dependency injection or validation framework?
Short answer
Use java.lang.reflect classes (Class.getDeclaredMethods(), Method.getAnnotation(YourAnnotation.class), Field.isAnnotationPresent()) to inspect a class's structure at runtime, checking for the presence of your custom RUNTIME-retention annotation and extracting its element values…
Advertisement
AModel answer
Use java.lang.reflect classes (Class.getDeclaredMethods(), Method.getAnnotation(YourAnnotation.class), Field.isAnnotationPresent()) to inspect a class's structure at runtime, checking for the presence of your custom RUNTIME-retention annotation and extracting its element values to drive behavior -- this is the fundamental mechanism underlying frameworks like Spring's @Autowired or Hibernate Validator's @NotNull, where annotation metadata is read reflectively to wire dependencies or apply validation rules without generated boilerplate.
public class AnnotationProcessor {
public static void invokeLoggable(Object obj) throws Exception {
for (Method method : obj.getClass().getDeclaredMethods()) {
if (method.isAnnotationPresent(Loggable.class)) {
Loggable ann = method.getAnnotation(Loggable.class);
System.out.println("Invoking logged method: " + ann.value());
method.invoke(obj);
}
}
}
}Real-world example
A lightweight in-house DI container scans classes for a custom @Inject annotation on fields, using reflection to instantiate and set the appropriate dependency, replicating a simplified version of what Spring's @Autowired does under the hood.
Likely follow-ups
- What's the performance cost of reflection-based annotation processing at runtime versus compile-time annotation processing?
- How does Java's annotation processing API (APT) differ from reading annotations reflectively at runtime?
Related topics