Java Reference ยท Language Features by Version
Custom annotations
Reference for declaring your own Java annotations with @interface: elements and defaults, @Retention, @Target, @Repeatable, and reading them by reflection.
You declare an annotation type with @interface. It looks like an interface whose methods are the annotation's elements. Where the annotation may be placed, and how long it is kept, are controlled by meta-annotations on the declaration: @Target and @Retention.
Declaring an annotation is only half the job. Something has to read it: the compiler (through an annotation processor), a build tool, or your own code at run time through reflection. Frameworks such as JUnit, Spring, Jakarta and Jackson work exactly this way.
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface Range { int min() default 0; int max(); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Declaring annotation types
- Elements are written as methods without parameters, with a return type of a primitive,
String,Class, an enum, another annotation, or a one-dimensional array of those. They cannot throw, be generic, or returnnull. default valuemakes an element optional. An element namedvaluecan be given alone:@Role("admin")is short for@Role(value = "admin"). Array elements accept braces, and a single value needs none:ports = 80.- An annotation with no elements is a marker annotation, like
@NotBlankabove. - Annotation types may not extend anything; implicitly they extend
java.lang.annotation.Annotation.
Meta-annotations
| Meta-annotation | Values | Meaning |
|---|---|---|
@Retention |
SOURCE, CLASS, RUNTIME |
How long the annotation lives. CLASS (the default) is stored in the class file but not available through reflection; RUNTIME is readable by reflection. |
@Target |
TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE, TYPE_PARAMETER, TYPE_USE, MODULE, RECORD_COMPONENT |
Where it may be placed. Without it, it can go on any declaration (not on type uses). |
@Repeatable(Container.class) |
a container annotation | Allows the same annotation more than once on one element. |
@Inherited |
none | Subclasses inherit a class-level annotation from the superclass. Has no effect on methods or interfaces. |
@Documented |
none | Includes the annotation in generated Javadoc. |
Reading annotations
The reflection methods are defined by AnnotatedElement, implemented by Class, Method, Field, Constructor, Parameter, RecordComponent, Package and Module:
| Method | Returns |
|---|---|
getAnnotation(Class<A>) |
the annotation, or null |
isAnnotationPresent(Class) |
boolean |
getAnnotations() |
all annotations, including inherited ones |
getDeclaredAnnotations() |
only those declared directly on the element |
getAnnotationsByType(Class<A>) |
an array that looks through repeatable containers |
Usage notes
- Only
RUNTIMEretention works with reflection. A framework that scans at build time (a processor) can useSOURCEorCLASS. - Annotation element values must be compile-time constants: literals,
static finalconstants, class literals and enum constants. - Reflection is slower than direct calls and is best done once, caching the result (frameworks scan at start-up).
@Target(TYPE_USE)allows annotations anywhere a type appears:List<@NonNull String>. Checkers use these.- Annotation processors (
javax.annotation.processing) can generate code or check rules at compile time; this is how Lombok-style tools and MapStruct work. - Do not overuse annotations for control flow. Code that behaves differently because of invisible metadata is hard to debug.