Sub topic 8
Declaring and applying annotations
An annotation attaches structured metadata to a program element, such as a class, method, or field. The annotation does not change what the code does. Other code reads it: the compiler, a build tool, or a framework using reflection. This chapter covers how to declare your own annotation type and how to apply it. It assumes you know core Java syntax, interfaces, enums, and arrays. The previous chapters on Class objects and inspecting members are also assumed. The next chapter covers the meta-annotations that control whether and where an annotation is visible.
Annotations you already use
Some annotations ship with Java:
| Annotation | Purpose |
|---|---|
| `@Override` | The compiler checks that the method really overrides a supertype method. |
| `@Deprecated` | Marks an element as discouraged. Callers get a compiler warning. |
| `@SuppressWarnings("unchecked")` | Silences named compiler warnings. |
| `@FunctionalInterface` | The compiler checks that the interface has exactly one abstract method. |
| `@SafeVarargs` | Asserts that a generic varargs method is safe. |
Each of these is an ordinary annotation type declared with the syntax below. Nothing about them is special to the language, except that the compiler knows how to act on them.
Declaring an annotation type
An annotation type is declared with @interface. Its body lists elements that look like parameterless methods.
@interface Label {
String value();
}The declaration creates a special kind of interface. Every annotation type implicitly extends java.lang.annotation.Annotation. That is why reflection returns annotation instances that you can call owner() or value() on.
Element declarations follow strict rules:
- No parameters and no
throwsclause. - No generic type parameters.
- The return type must be one of: a primitive,
String,Class(orClass<? extends X>), an enum, another annotation type, or a one-dimensional array of those. - An element may have a
defaultvalue. An element without one is required at every use. nullis never a legal value, as a default or as an argument.
A marker, a single-value annotation, and a full one
Three shapes cover most annotations.
A marker annotation has no elements. Its mere presence is the information, as with @Override.
A single-element annotation names its element value. The name value is special, because it lets the user omit the name at the use site.
A full annotation has several elements, some with defaults.
The following program declares all three, applies them, and reads the values back. The @Retention line is needed so the annotation survives to runtime. The next chapter explains why.
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
enum Status { OPEN, DONE }
@Retention(RetentionPolicy.RUNTIME)
@interface Task {
String owner();
int priority() default 3;
String[] tags() default {};
Status status() default Status.OPEN;
}
@Retention(RetentionPolicy.RUNTIME)
@interface Label {
String value();
}
@Retention(RetentionPolicy.RUNTIME)
@interface Experimental {}
@Task(owner = "ada", priority = 1, tags = {"billing", "urgent"})
@Label("Monthly report")
@Experimental
class Report {}
@Task(owner = "linus", tags = "cleanup")
class Cleanup {}
public class AnnotationBasics {
public static void main(String[] args) {
Task t = Report.class.getAnnotation(Task.class);
System.out.println(t.owner());
System.out.println(t.priority());
System.out.println(Arrays.toString(t.tags()));
System.out.println(t.status());
System.out.println(Report.class.getAnnotation(Label.class).value());
System.out.println(Report.class.isAnnotationPresent(Experimental.class));
Task c = Cleanup.class.getAnnotation(Task.class);
System.out.println(c.priority());
System.out.println(Arrays.toString(c.tags()));
}
}The output is:
ada
1
[billing, urgent]
OPEN
Monthly report
true
3
[cleanup]Cleanup supplies only owner and one tag. The compiler fills priority and status from the defaults, and the reflected annotation reports them as if they had been written.
Syntax for applying annotations
An annotation is applied by writing @ and the type name before the element it describes. The rules for the argument list are:
- Named pairs.
@Task(owner = "ada", priority = 1). Order does not matter. - Shorthand. If
valueis the only element you are setting, write@Label("Monthly report"). If the annotation has other elements with defaults, the shorthand still works as long as you set onlyvalue. - No arguments.
@Experimentaland@Experimental()are equivalent. Elements without defaults make the parentheses mandatory. - Arrays. Use braces for several values:
tags = {"a", "b"}. A single value may drop the braces:tags = "cleanup". An empty array is{}. - Enums. Write the constant without its type name:
status = Status.DONEis accepted, and so is a static import of the constant. - Class values. Write a class literal such as
handler = Runnable.class.
Several different annotations can be stacked on one element, in any order. The same annotation type cannot appear twice on one element unless its declaration opts in with @Repeatable, which a later chapter section covers.
Values must be compile-time constants
An annotation argument is evaluated by the compiler, not at runtime. Allowed values are literals, static final constants initialized with constant expressions, enum constants, class literals, other annotations, and arrays of those.
class Limits {
static final int MAX = 10;
static final int COMPUTED = Integer.parseInt("10");
}
@interface Cap {
int value();
}
@Cap(Limits.MAX) // legal: constant expression
class A {}
// @Cap(Limits.COMPUTED) // compile error: not a constant expression
// class B {}Constant expressions also allow Limits.MAX * 2 and string concatenation of constants. A method call, a new expression, or a non-final field is rejected.
Where an annotation may appear
By default an annotation without an @Target can be applied to any declaration. That covers classes, interfaces, enums, methods, fields, constructors, parameters, local variables, packages, and type parameters. Since Java 8, the use of a type, as in List<@NonNull String>, is allowed only when the annotation's @Target includes TYPE_USE. Restricting where your annotation may appear is the job of @Target, which the next chapter covers.
Here is how placement looks on common elements:
class Service {
@Label("id")
private int id;
@Label("constructor")
Service(@Label("param") int id) {
@Label("local")
int copy = id;
this.id = copy;
}
@Label("method")
void run() {}
}This compiles, because Label has no @Target restriction. Annotations on local variables are not visible to reflection even with runtime retention, since local variables do not exist in the reflective model. Only tools that read the source or bytecode can see them.
Common compile errors
| Mistake | Compiler complaint |
|---|---|
| `@Task(priority = 1)` with `owner` missing | The annotation is missing a default value for the element `owner`. |
| `@Task(owner = null)` | An annotation value must be a constant expression. `null` is not allowed. |
| `int[] nums() default null;` | The default value must be a constant, and `null` is not valid. |
| `List<String> items();` in an annotation | The element type is not valid. Use an array such as `String[]`. |
| `@Label("a") @Label("b")` on one class | The annotation is not repeatable. |
| `@interface Node { Node child(); }` | Cyclic annotation element type. An annotation cannot contain itself. |
| `@Task(owner = "a", priority = "high")` | `String` cannot be converted to `int`. |
Two further traps are less visible. First, an annotation by itself does nothing. If no compiler, tool, or framework reads @Task, it has no effect. Second, adding an element without a default breaks every existing use of the annotation. When you evolve an annotation that others already use, give new elements defaults.
Exercise
You declare @interface Route { String path(); String method() default "GET"; String[] roles() default {}; }. Write one valid annotation use that sets the path to "/users" and the roles to "admin" and "staff". Then explain what method() returns when read by reflection, and why @Route alone on a class would not compile.
Show answer
A valid use is @Route(path = "/users", roles = {"admin", "staff"}). The compiler fills in the default for method, so method() returns "GET" when read reflectively (assuming runtime retention). @Route alone fails because path has no default, so every use must supply it.
Exercise
Which of these annotation element declarations is illegal, and why? (a) Class<?> type(); (b) Status[] states() default {}; (c) List<String> names(); (d) Task nested(); where Task is another annotation type.
Show answer
(c) is illegal. An element cannot have a generic collection type, and the allowed types are primitives, String, Class, enums, annotations, and one-dimensional arrays of these. Declaration (a) is legal because Class is allowed. Declaration (b) is an array of an enum. Declaration (d) is an annotation-typed element, provided Task does not contain nested in a cycle.