Lesson · Annotations & Annotation Processing
Custom Annotations
11 min readCustom Annotations
An annotation type is an interface whose methods are questions a consumer will ask. This lesson writes one from scratch: legal element types, defaults, the value() shorthand, the marker and single-element shapes, type annotations for static analysis, and what the compiler enforces at every use site.
An annotation type is an interface with questions in it
@interface declares an annotation type. The compiler turns it into an interface extending java.lang.annotation.Annotation, and each method you declare becomes an element: a question the consumer will ask. There is no body to write and no behaviour to inherit, because the values are stored by the compiler at each use site and read back later, by javac, by a processor, or by reflection.
Declaring one is cheap: public @interface Retry {} is a legal marker with no elements at all. The design effort goes into what comes next, because every element you add is something every consumer has to consider and every caller may have to supply.
An annotation type is an interface where the methods are questions the consumer will ask.
Elements: what an annotation can carry
An element looks like a method with no parameters, and its return type is restricted to the types the compiler can store and compare as a constant. Try to carry anything else and the compiler stops you at the declaration, long before a caller sees the annotation.
| Element type | Example | Legal |
|---|---|---|
| a primitive, never void | int maxAttempts(); | yes |
| String | String topic() default "orders"; | yes |
| Class, including parameterized forms | Class<? extends Throwable>[] retryOn(); | yes |
| an enum type | TimeUnit unit() default TimeUnit.SECONDS; | yes |
| another annotation type | Schedule schedule(); | yes |
| a single-dimensional array of any of those | int[] ports(); | yes |
| a generic type such as List<String> | List<String> names(); | no, the declaration does not compile |
| null as a default | String note() default null; | no, an element is never null |
| any other reference type | Optional<String> note(); | no |
- An element is a method with no parameters: no type parameters, no throws clause, and the compiler rejects the declaration if any of that appears.
- No default means required: every use site must supply the value, and forgetting one is a compile error at the call site, not a warning.
- Arrays are single-dimensional only: for anything richer, declare a second annotation type or encode the data in a String the consumer parses.
- An annotation type is still an interface: it may also declare constant fields and member types, which is how complex annotations were built before nested annotations were allowed.
Elements are the whole payload. An annotation cannot compute, cache or validate anything on its own; that is the consumer's job.
Anatomy · one @interface declaration, part by part
the structure every consumer reads
an element is a method
- Return type: the element type, restricted to primitives, String, Class, enums, annotation types, and single-dimensional arrays of those.
- Name: the element name. An element named value unlocks the shorthand at the use site, so @Retry(5) means @Retry(value = 5).
- default: optional, and read at every use site that omits the element, so the policy lives in this line for all callers.
- Brackets: arrays are legal and single-dimensional; a list of values is an array of class literals, constants or annotation literals.
- Cap: meta-annotations on the declaration decide the retention, the target and whether repeats are allowed.
what this declaration unlocks at the use site
Defaults and the value() shorthand
A default makes an element optional. At the use site, an omitted element reads back as the value declared here, and the decision belongs to the annotation author, once, rather than to every caller, forever. Defaults are also the part of an annotation that is easiest to change later, because new elements can arrive with one while existing callers keep compiling.
value() is not special syntax in the element set; it is a naming convention the grammar notices. If the element is called value, the name may be omitted at the use site, which is why tiny annotations read like function calls.
- Default equals optional: add one whenever a sensible policy exists, so the common use is @Retry and the rare use is @Retry(maxAttempts = 5).
- Required equals tax: an element without a default must be spelled out by every caller, in every codebase, for as long as the annotation lives. Charge it only when there is no honest default.
- The shorthand: with an element named value, @Limit(10) means @Limit(value = 10). When value is an array, a single value may also drop the braces: @Roles("admin") means @Roles(value = { "admin" }).
- Elements are named at the use site, not positional: only value gets the shorthand, so order in the declaration never matters and duplicates are rejected.
A default is a decision you make once for every caller; a required element is a decision you force on every caller.
What the compiler enforces at the use site
Most of the value of declaring an annotation properly is that the compiler checks every use against the declaration. The errors all arrive at compile time, which is the cheapest possible moment to find them.
- Element type: @Retry(maxAttempts = "five") fails because the element is an int; the same check rejects an int where a String is expected.
- Required elements: a declaration with no default must be supplied, and the compiler names the element that is missing.
- Target: with @Target(METHOD), writing the annotation on a field is a compile error; the annotation is not applicable to that declaration.
- Element names: a name that does not exist on the annotation type fails, and an element given twice fails as well.
- Retention plays no part in any of this. These checks belong to the compiler and happen whatever the retention is.
If an annotation use compiled, its values and its target were legal. If the consumer still does not see it, the problem is retention or the reader, never the use site.
Custom annotations · building @Retry
the annotation so far
no elements yet
javac and the reader
nothing declared yet: the claim is still an English sentence
Every annotation starts as a sentence. If nobody can state the claim, the declaration has nothing to say, however it is shaped.
Marker, single element, multi-element, type annotation
The shape of the annotation should match the shape of the claim:
- Marker: no elements at all, so presence is the whole message. Right when the claim has no parameters, such as a method being idempotent or a type being thread-safe.
- Single element: one element, conventionally named value, so the shorthand applies. Right for a name, a limit, a label, or anything that reads like a function argument.
- Multi-element policy: several named elements, each with a sensible default, as in the retry policy built in the play area. Right when the annotation configures behaviour rather than labelling it.
- Type annotation (TYPE_USE): a declaration whose target is TYPE_USE can be written on any type, so nullness annotations from JSpecify or the Checker Framework attach to the type itself: List<@NonNull String>. A static analyser is the consumer, and javac merely stores what you wrote.
- Repeatable: declaring @Repeatable and a container lets one element carry the annotation several times, with the container mechanics owned by the meta-annotations lesson. Reach for it only when a genuine list belongs on one declaration.
Pick the smallest shape that carries the claim: markers read best, and every element you add without a default is a question every caller must answer.
A required element is a tax on every caller
An element with no default must be spelled out at every single use, and the compiler will make sure nobody forgets. That is the right choice for a value only the caller knows, such as an owner, a route or a queue name. It is the wrong choice for a policy that has an obvious default: maxAttempts = 3 is a decision you can make once, and without the default every caller makes it again, in a hurry, differently. Worse, when the policy needs to change later, a default lets you move it in one place, while a required element means editing every use site in every repository. Defaults are API design, not laziness; choose them while you can still see every caller.
Interview angles
Can an annotation carry a List<String> element?+
No. Element types are primitives (never void), String, Class including parameterized forms such as Class<? extends Throwable>, enum types, other annotation types, and single-dimensional arrays of those. Generics are rejected at the declaration.
The restriction follows from how annotations are stored and compared: every value must be expressible as a constant in the class file and comparable by the annotation contract, which is why the list stops exactly where it does.
What exactly is the value() shorthand?+
If the annotation declares an element named value, a single-element use may omit the name: @Limit(10) means @Limit(value = 10). If value is an array, the braces may be dropped for a single value as well.
Common misconception: That value() is privileged syntax inside the compiler's element set. It is a naming convention: rename the element to limit() and the same call stops compiling.
When would you make an annotation TYPE_USE instead of a declaration annotation?+
When the claim is about a type rather than a member: nullness, immutability, units, taint. A static analyser can then read it wherever the type appears, including inside generics such as List<@NonNull String>, which a declaration annotation cannot express.
TYPE_USE covers every type context and, since Java 8, also class declarations and type parameter declarations, so one target serves every position a type checker cares about.
Why give every element a default?+
Because a required element is charged to every caller and every future use, while a default lets the common case stay short. The trade is that an omitted element silently takes a policy that lives in the annotation declaration, so changing a default changes behaviour at every use site that omitted it.
Follow-up: So when do you make an element required? When there is no defensible default: an owner, a destination, a credential name, anything the annotation author cannot know.