Sub topic 9
Meta-annotations: Retention, Target, Inherited, Repeatable
This chapter assumes you can declare a simple annotation with @interface and apply it to a class, and that you know the basics of Class and getAnnotation from earlier chapters. Here you will learn the four annotations that control how other annotations behave, and the mistakes that come from leaving them out.
What a meta-annotation is
A meta-annotation is an annotation that you place on an annotation declaration. It does not change what your annotation means. It changes the rules around it: how long the compiler keeps it, where it may be written, whether subclasses see it, and whether it may appear more than once.
All four live in java.lang.annotation. If you leave them out, the defaults are often not what you want. The most common surprise is that an annotation you wrote is invisible to reflection.
@Retention: how long the annotation survives
@Retention takes a RetentionPolicy value. It decides at which stage of the build and run cycle the annotation is discarded.
| Policy | In source code | In the `.class` file | Readable by reflection |
|---|---|---|---|
| `SOURCE` | yes | no | no |
| `CLASS` (default) | yes | yes | no |
| `RUNTIME` | yes | yes | yes |
SOURCE suits annotations meant only for the compiler or tools that read source, such as @Override. CLASS keeps the annotation in the bytecode for tools that inspect class files, but the JVM does not expose it. Only RUNTIME is visible to the reflection API.
This program applies one annotation of each policy to the same class and asks reflection what it can see:
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.SOURCE)
@interface FromSource {}
@interface FromClassFile {}
@Retention(RetentionPolicy.RUNTIME)
@interface Visible {}
@FromSource
@FromClassFile
@Visible
public class RetentionDemo {
public static void main(String[] args) {
for (Annotation a : RetentionDemo.class.getAnnotations()) {
System.out.println(a.annotationType().getSimpleName());
}
}
}It prints only Visible. The other two exist in source or in the class file, but reflection never sees them.
@Target: where the annotation may be written
@Target takes an array of ElementType constants and limits the places where the annotation may be applied. The compiler enforces this, so a misplaced annotation is an error at build time instead of a silent no-op at run time.
| ElementType | Applies to |
|---|---|
| `TYPE` | classes, interfaces, enums, annotation types |
| `FIELD` | fields, including enum constants |
| `METHOD` | methods |
| `PARAMETER` | method and constructor parameters |
| `CONSTRUCTOR` | constructors |
| `LOCAL_VARIABLE` | local variables |
| `ANNOTATION_TYPE` | annotation declarations (used by meta-annotations) |
| `TYPE_USE` | any place a type is written, such as `List<@NonNull String>` |
You can list several: @Target({ElementType.FIELD, ElementType.METHOD}). Without @Target, the annotation may go on any declaration, but not on type uses.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Timed {}
class Service {
@Timed
void work() {}
// @Timed // compile error: annotation type not applicable to this kind of declaration
// int counter;
}
public class TargetDemo {
public static void main(String[] args) throws Exception {
System.out.println(Service.class
.getDeclaredMethod("work")
.isAnnotationPresent(Timed.class));
}
}This prints true. If you uncomment the field annotation, the file no longer compiles. Narrow targets are worth the typing, because a validator written for fields should reject @NotBlank placed on a method.
@Inherited: visibility through class inheritance
By default, an annotation on a superclass is not seen on its subclasses. Marking the annotation type with @Inherited changes that for one case only: when you ask a class for an annotation, and the class has none of that type itself, the lookup continues up the superclass chain.
The limits matter:
- It works only for annotations applied to classes. Methods, fields, and parameters are unaffected.
- It follows
extendsonly. Annotations on interfaces are never inherited by implementing classes. - It affects
getAnnotationandisAnnotationPresent, but notgetDeclaredAnnotation, which looks only at the class itself.
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@interface Audited {}
@Audited
class Base {}
class Child extends Base {}
@Audited
interface Api {}
class Impl implements Api {}
public class InheritedDemo {
public static void main(String[] args) {
System.out.println(Child.class.isAnnotationPresent(Audited.class));
System.out.println(Child.class.getDeclaredAnnotation(Audited.class));
System.out.println(Impl.class.isAnnotationPresent(Audited.class));
}
}The output is true, null, false. Child sees the annotation through its superclass, but it does not declare it. Impl sees nothing, because Api is an interface.
@Repeatable: the same annotation more than once
Normally you may apply an annotation to an element only once. @Repeatable lifts that, but it needs a second annotation, called the container, that holds the repeated values. The compiler does the wrapping: when you write two @Role annotations, it generates one @Roles annotation containing both.
The container must follow these rules, and the compiler rejects a violation:
- It declares a
value()method returning an array of the repeatable annotation type. - Its retention is at least as long as the repeatable annotation's.
- Its targets are the same as, or fewer than, the repeatable annotation's.
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Roles {
Role[] value();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Repeatable(Roles.class)
@interface Role {
String value();
}
@Role("admin")
@Role("auditor")
class Account {}
@Role("guest")
class Visitor {}
public class RepeatableDemo {
public static void main(String[] args) {
System.out.println(Account.class.getAnnotation(Role.class));
System.out.println(Account.class.getAnnotation(Roles.class).value().length);
System.out.println(Account.class.getAnnotationsByType(Role.class).length);
System.out.println(Visitor.class.getAnnotation(Roles.class));
System.out.println(Visitor.class.getAnnotationsByType(Role.class).length);
}
}This prints null, 2, 2, null, 1. Two repeated @Role annotations exist only inside the generated @Roles, so getAnnotation(Role.class) returns null. A single @Role is not wrapped, so getAnnotation(Roles.class) returns null for Visitor.
Common errors and a checklist
- Annotation is never found. The retention is
CLASSorSOURCE. Add@Retention(RetentionPolicy.RUNTIME). - "Annotation type not applicable to this kind of declaration." The element type is missing from
@Target, or you placed the annotation on the wrong kind of element. - A subclass does not see a method annotation.
@Inheritednever applies to methods. Walk the class hierarchy yourself and check overridden methods. - An interface annotation is not found on the implementing class.
@Inheritedignores interfaces. SearchgetInterfaces()explicitly. getAnnotationreturns null for a repeated annotation. Read the container, or usegetAnnotationsByType.- Compile error on
@Repeatable. The container is missingvalue(), has a shorter retention, or has a wider target.
@Documented, a fifth meta-annotation, only tells Javadoc to include the annotation in generated documentation. It has no effect on reflection.
Exercise
You write @Retention(RetentionPolicy.RUNTIME) @Inherited @interface Tag {}, then @Tag class A {} and class B extends A {}. For B.class, what do isAnnotationPresent(Tag.class) and getDeclaredAnnotation(Tag.class) return, and what changes if Tag is applied to an interface I that B implements?
Show answer
isAnnotationPresent(Tag.class) returns true because @Inherited lets the lookup continue to the superclass A. getDeclaredAnnotation(Tag.class) returns null because B does not declare it. If Tag is applied only to an interface I that B implements, both calls return false and null, because @Inherited follows extends only and ignores interfaces.
Exercise
A class carries @Role("a") @Role("b"), where Role is @Repeatable(Roles.class). Why does getAnnotation(Role.class) return null, and which call returns both values regardless of how many @Role annotations are present?
Show answer
With two or more occurrences, the compiler stores them inside a single generated @Roles container, so no standalone @Role exists on the class. getAnnotationsByType(Role.class) returns all the values for zero, one, or many occurrences, because it unwraps the container when needed.