Annotations and retention
What you will learn
An annotation attaches structured metadata to a declaration or type use. It does not execute a task by itself. A compiler, processor or application must interpret it. Retention determines whether ordinary runtime reflection can see it.
- Declare an annotation with a typed element and default.
- Choose retention and target based on who reads the metadata.
- Read optional, repeated and inherited class annotations safely.
Each example is a complete Main.java file. Use a fresh directory, javac --release 21 Main.java, then java Main. No external dependencies. Compile with -proc:none to disable annotation processors. Run only these reviewed examples in a fresh lab-owned directory. Service fixtures create and clean up fixed local registration resources. No external plugins or private access bypass.
Read a label with a default
import java.lang.annotation.*;import java.lang.reflect.*;import java.lang.invoke.*;import java.util.*;import java.nio.file.*;import java.nio.charset.StandardCharsets;import java.net.URLClassLoader;import java.net.URL;public class Main { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @interface Label { String value(); int version() default 1; } @Label("invoice") static class Invoice {} static class Plain {} public static void main(String[] args) throws Throwable { Label label = Invoice.class.getAnnotation(Label.class); System.out.println(label.value()); System.out.println(label.version()); System.out.println(Plain.class.getAnnotation(Label.class) == null); }}Expected output:
invoice1trueThe first class has explicit metadata; the default version is supplied by the annotation declaration. An absent label is null.
Declaration and built-in annotations
Declare an annotation interface with @interface. Elements have restricted types: primitives, String, Class, enums, annotations and one-dimensional arrays of these types. A default is optional; missing required elements are compile errors. @Override checks a claimed override, @Deprecated signals discouraged use, @FunctionalInterface checks interface shape, and @SuppressWarnings scopes compiler warnings. None is a general instruction to execute application behavior.
Retention and targets
SOURCE is discarded by the compiler; CLASS is the default and is recorded in the class file where applicable but is not exposed by ordinary runtime reflection; RUNTIME is available through reflection for supported elements. @Target limits use, such as TYPE, METHOD or FIELD; TYPE_USE describes type positions rather than just declarations. Local variable declaration annotations have additional class-file restrictions. @Repeatable names a container whose value is an array of the repeated annotation; align retention and targets. @Inherited only affects class annotation lookup along superclass chains, not interface implementations or method overriding.
Processors versus readers
An annotation processor participates in compilation rounds, can inspect declarations and generate source or diagnostics. Runtime reflection instead reads already compiled metadata. Processors are executable build dependencies; use only reviewed processors, pin versions and keep them disabled when unnecessary. These examples use -proc:none. No processor execution is required. A metadata reader must handle missing annotation values explicitly; use fixed known classes and avoid scanning unknown artifacts.
Compare retention policies
import java.lang.annotation.*;import java.lang.reflect.*;import java.lang.invoke.*;import java.util.*;import java.nio.file.*;import java.nio.charset.StandardCharsets;import java.net.URLClassLoader;import java.net.URL;public class Main { @Retention(RetentionPolicy.SOURCE) @interface SourceNote {} @interface ClassNote {} @Retention(RetentionPolicy.RUNTIME) @interface RuntimeNote {} @SourceNote @ClassNote @RuntimeNote static class Sample {} public static void main(String[] args) throws Throwable { System.out.println(Sample.class.isAnnotationPresent(SourceNote.class)); System.out.println(Sample.class.isAnnotationPresent(ClassNote.class)); System.out.println(Sample.class.isAnnotationPresent(RuntimeNote.class)); }}Expected output:
falsefalsetrueOnly the runtime-retained declaration is visible to reflection.
Read repeatable labels
import java.lang.annotation.*;import java.lang.reflect.*;import java.lang.invoke.*;import java.util.*;import java.nio.file.*;import java.nio.charset.StandardCharsets;import java.net.URLClassLoader;import java.net.URL;public class Main { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Repeatable(Tags.class) @interface Tag { String value(); } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @interface Tags { Tag[] value(); } @Tag("billing") @Tag("reviewed") static class Report {} public static void main(String[] args) throws Throwable { for (Tag tag : Report.class.getAnnotationsByType(Tag.class)) System.out.println(tag.value()); }}Expected output:
billingreviewedThe by-type lookup expands the container in declaration order.
Declared versus inherited
import java.lang.annotation.*;import java.lang.reflect.*;import java.lang.invoke.*;import java.util.*;import java.nio.file.*;import java.nio.charset.StandardCharsets;import java.net.URLClassLoader;import java.net.URL;public class Main { @Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @interface Reviewed {} @Reviewed static class Parent {} static class Child extends Parent {} public static void main(String[] args) throws Throwable { System.out.println(Child.class.isAnnotationPresent(Reviewed.class)); System.out.println(Child.class.getDeclaredAnnotation(Reviewed.class) == null); }}Expected output:
truetrueInherited lookup finds the superclass annotation; declared lookup does not.
Common mistakes
Do not assume a custom annotation automatically validates an invoice, or call value() on a possibly absent annotation. Do not select RUNTIME for metadata that only a compiler needs. Do not suppress warnings to hide unsafe casts.
Practice
Using Label, Invoice and Plain, print a label for each known class, using unlabeled when metadata is missing.
Expected output:
invoiceunlabeledCompare your answer with the manual practice criteria.
Official reading: JLS 9 · Retention · Target · Repeatable · Processor. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Annotations and retention — knowledge check
Original metadata, reflection and service discovery questions. Java 21-compatible scope.
What causes custom annotation behavior?
Which retention exposes annotations to reflection?
What is default retention?
Which method expands repeatable containers?
What does @Inherited affect?