Sub topic 10
Reading annotations at runtime
This chapter covers how to read annotations from classes, fields, methods, and parameters at runtime. It also covers the lookup rules that most often cause a null result.
It assumes you can declare an annotation with @Retention and @Target, get a Class object, and list members with getDeclaredFields() and getDeclaredMethods(). Earlier chapters cover all of these.
The AnnotatedElement interface
Every program element that can carry an annotation implements java.lang.reflect.AnnotatedElement. This includes Class, Field, Method, Constructor, Parameter, Package, and RecordComponent. Because they share this interface, the same reading code works on all of them.
| Method | Returns | Notes |
|---|---|---|
| `getAnnotation(Class<A>)` | the annotation or `null` | Includes inherited annotations (see below). |
| `isAnnotationPresent(Class)` | `boolean` | Shorthand for a null check. |
| `getAnnotations()` | `Annotation[]` | Declared plus inherited. |
| `getDeclaredAnnotations()` | `Annotation[]` | Only those written directly on this element. |
| `getAnnotationsByType(Class<A>)` | `A[]` | Sees through repeatable containers. Never `null`. |
| `getDeclaredAnnotationsByType(Class<A>)` | `A[]` | Same, without inheritance. |
A first read
The example defines an annotation that is allowed on types and methods. It reads the annotation from a class and from each of its methods.
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.TYPE, ElementType.METHOD})
@interface Command {
String name();
int retries() default 0;
}
@Command(name = "report")
class ReportJob {
@Command(name = "run", retries = 3)
public void run() { }
public void helper() { }
}
public class ReadDemo {
public static void main(String[] args) {
Class<?> type = ReportJob.class;
Command onClass = type.getAnnotation(Command.class);
System.out.println(onClass.name() + " retries=" + onClass.retries());
for (Method m : type.getDeclaredMethods()) {
if (m.isAnnotationPresent(Command.class)) {
Command c = m.getAnnotation(Command.class);
System.out.println(m.getName() + " -> " + c.name()
+ " retries=" + c.retries());
}
}
}
}This prints report retries=0 and then run -> run retries=3. The class annotation uses the default for retries. The method helper has no annotation, so it is skipped.
The return value of getAnnotation is typed as the annotation interface itself, so no cast is needed. You read each element by calling the method of the same name, such as c.name().
Why the result is sometimes null
A null from getAnnotation usually has one of four causes. Check them in this order.
- Retention is not RUNTIME. The default retention is
CLASS. The compiler writes such annotations into the.classfile, but the JVM does not load them. Reflection cannot seeSOURCEorCLASSannotations, and it gives no error. It simply returnsnull. - The annotation sits on a different element. An annotation on a field is not visible from the getter method, and the reverse is also true. A
@Targetwith several element types can hide this mistake. - Inheritance does not apply (next section).
- The annotation is repeatable and was applied more than once (see below).
What you actually receive
The object returned by getAnnotation is a JDK-generated proxy that implements your annotation interface. Calling name() on it reads the value stored in the class file, or the declared default if none was written. You can call annotation.annotationType() to get the interface back as a Class. toString() prints something like @Command(name="run", retries=3), though the exact format differs between JDK versions.
Element values are limited to primitives, String, Class, enums, other annotations, and arrays of these. Reading a Class element can throw TypeNotPresentException if the referenced class is missing at runtime.
Inheritance and repeatable annotations
Two meta-annotations change what the lookup methods return. @Inherited lets a class annotation be found on subclasses. @Repeatable lets an annotation appear more than once on the same element.
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Target(ElementType.TYPE)
@interface Audited { }
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Repeatable(Tags.class)
@interface Tag {
String value();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Tags {
Tag[] value();
}
@Audited
@Tag("a")
@Tag("b")
class Base { }
class Child extends Base { }
public class LookupDemo {
public static void main(String[] args) {
System.out.println(Child.class.isAnnotationPresent(Audited.class));
System.out.println(Child.class.getDeclaredAnnotations().length);
System.out.println(Base.class.getAnnotation(Tag.class));
for (Tag t : Base.class.getAnnotationsByType(Tag.class)) {
System.out.println("tag " + t.value());
}
System.out.println(Base.class.getAnnotation(Tags.class).value().length);
}
}The output is:
true
0
null
tag a
tag b
2Child reports @Audited as present because the annotation is @Inherited, but getDeclaredAnnotations() shows nothing written on Child itself. Base.class.getAnnotation(Tag.class) is null. With two @Tag annotations, the compiler wraps them in a single @Tags container, so no @Tag is directly present. getAnnotationsByType looks inside the container and returns both tags. It also works when only one @Tag is written.
The container annotation needs a retention at least as long as the repeatable annotation's, or the code will not compile.
The diagram shows how the lookup methods decide what to return.
Parameter annotations
Parameter annotations come back as a two-dimensional array. The outer index is the parameter position, and the inner array holds that parameter's annotations. The inner array is empty for parameters with none, so a parameter never maps to null.
import java.lang.annotation.Annotation;
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.PARAMETER)
@interface Named {
String value();
}
class Service {
public void send(@Named("to") String to, @Named("body") String body, int priority) { }
}
public class ParamDemo {
public static void main(String[] args) throws NoSuchMethodException {
Method m = Service.class.getMethod("send", String.class, String.class, int.class);
Annotation[][] all = m.getParameterAnnotations();
for (int i = 0; i < all.length; i++) {
System.out.print("param " + i + ":");
for (Annotation a : all[i]) {
if (a instanceof Named) {
System.out.print(" " + ((Named) a).value());
}
}
System.out.println();
}
}
}The output is param 0: to, param 1: body, and param 2: with nothing after it. Method.getParameters() returns Parameter objects, which implement AnnotatedElement and are often easier to loop over. Without the -parameters compiler flag, Parameter.getName() returns arg0, arg1, and so on. This is why annotations such as @Named exist: they carry names in a form that survives compilation.
Habits that prevent bugs
- Prefer
getDeclaredFields()andgetDeclaredMethods()over theget...variants when scanning your own classes. Thegetvariants return only public members, including inherited ones. - Prefer
isAnnotationPresentfor marker annotations that have no elements. - Cache the results of annotation scans. Reading annotations parses class-file data on first access, and the JDK caches each element's result, but your own derived data, such as a list of validated fields, is worth keeping in a map keyed by
Class. - Treat a missing annotation as a normal case. Do not assume
getAnnotationreturns a value, and check fornullbefore calling its elements. - Bridge methods and synthetic members can appear in
getDeclaredMethods(). If duplicates show up, callisBridge()orisSynthetic()to filter them.
Exercise
A class Base is annotated with @Audited, which has RUNTIME retention but is not marked @Inherited. Child extends Base. What do Child.class.getAnnotation(Audited.class) and Child.class.getDeclaredAnnotations().length return? What changes if you add @Inherited to Audited?
Show answer
Both calls give no annotation: getAnnotation returns null and the length is 0, because the annotation is not inherited and is not written on Child. After adding @Inherited, getAnnotation(Audited.class) returns the annotation from Base, since the lookup walks up the superclass chain. getDeclaredAnnotations().length is still 0, because that method never includes inherited annotations.