Sub topic 10
Reading annotations at runtime
This chapter assumes you can declare an annotation and apply it, and that you know the meta-annotations @Retention and @Target. It also assumes you can list a class's fields and methods with reflection.
The AnnotatedElement interface
Class, Field, Method, Constructor, Parameter, and Package all implement AnnotatedElement. That interface is the single entry point for reading annotations. Its main methods are:
| Method | Returns |
|---|---|
| `getAnnotation(Class<A>)` | The annotation, or `null` if absent |
| `isAnnotationPresent(Class)` | `true` or `false` |
| `getAnnotations()` | All annotations, including inherited ones |
| `getDeclaredAnnotations()` | Only those written directly on the element |
| `getAnnotationsByType(Class<A>)` | An array that also unpacks repeatable annotations |
Reading a method annotation
The program below finds every method marked with @Route and prints its elements.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Route {
String path();
int priority() default 0;
}
class Controller {
@Route(path = "/home")
public void home() { }
@Route(path = "/admin", priority = 5)
public void admin() { }
public void helper() { }
}
public class ReadDemo {
public static void main(String[] args) {
for (Method m : Controller.class.getDeclaredMethods()) {
if (m.isAnnotationPresent(Route.class)) {
Route r = m.getAnnotation(Route.class);
System.out.println(m.getName() + " -> " + r.path()
+ " (priority " + r.priority() + ")");
}
}
}
}The output has two lines, one for home and one for admin. Their order can vary, because getDeclaredMethods() does not guarantee any order. If order matters, sort the results yourself, for example by priority.
The object returned by getAnnotation is a proxy that the JVM generates. It implements your annotation interface, and calls such as r.path() read values stored in the class file.
Retention decides what you can see
Only annotations with RetentionPolicy.RUNTIME can be read this way.
Common errors
getAnnotationreturnsnullfor an annotation that is clearly present. The usual cause is a missing@Retention(RetentionPolicy.RUNTIME). The default retention isCLASS.- A class annotation is missing on a subclass. Annotations on a class are inherited only if the annotation type itself is marked
@Inherited. Even then, this applies only to class-level annotations. It does not apply to methods or interfaces. - Repeated annotations are not found. When an annotation is repeated, the compiler wraps the copies in a container annotation.
getAnnotation(Tag.class)then returnsnullwhen there are two or more copies. UsegetAnnotationsByType(Tag.class)instead. - Parameter annotations are not on the
Method. Usemethod.getParameters()and callgetAnnotationon eachParameter.getParameterAnnotations()also works and returns a two-dimensional array.
Exercise
A field is annotated with @NotBlank, but field.getAnnotation(NotBlank.class) returns null. The annotation is declared with @Target(ElementType.FIELD). What is the most likely cause, and how do you fix it?
Show answer
The annotation lacks @Retention(RetentionPolicy.RUNTIME), so it uses the default CLASS retention and is not available to reflection. Add @Retention(RetentionPolicy.RUNTIME) to the annotation declaration.