Annotation types are defined with @interface
. Parameters are defined similar to methods of a regular interface.
@interface MyAnnotation {
String param1();
boolean param2();
int[] param3(); // array parameter
}
@interface MyAnnotation {
String param1() default "someValue";
boolean param2() default true;
int[] param3() default {};
}
Meta-annotations are annotations that can be applied to annotation types. Special predefined meta-annotation define how annotation types can be used.
The @Target
meta-annotation restricts the types the annotation can be applied to.
@Target(ElementType.METHOD)
@interface MyAnnotation {
// this annotation can only be applied to methods
}
Multiple values can be added using array notation, e.g. @Target({ElementType.FIELD, ElementType.TYPE})
ElementType | target | example usage on target element |
---|---|---|
ANNOTATION_TYPE | annotation types |
|
CONSTRUCTOR | constructors |
|
FIELD | fields, enum constants |
|
LOCAL_VARIABLE | variable declarations inside methods |
|
PACKAGE | package (in package-info.java ) |
|
METHOD | methods |
|
PARAMETER | method/constructor parameters |
|
TYPE | classes, interfaces, enums |
|
ElementType | target | example usage on target element |
---|---|---|
TYPE_PARAMETER | Type parameter declarations |
|
TYPE_USE | Use of a type |
|
The @Retention
meta-annotation defines the annotation visibility during the applications compilation process or execution. By default, annotations are included in .class
files, but are not visible at runtime. To make an annotation accessible at runtime, RetentionPolicy.RUNTIME
has to be set on that annotation.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
// this annotation can be accessed with reflections at runtime
}
RetentionPolicy | Effect |
---|---|
CLASS | The annotation is available in the .class file, but not at runtime |
RUNTIME | The annotation is available at runtime and can be accessed via reflection |
SOURCE | The annotation is available at compile time, but not added to the .class files. The annotation can be used e.g. by an annotation processor. |
The @Documented
meta-annotation is used to mark annotations whose usage should be documented by API documentation generators like javadoc. It has no values. With @Documented
, all classes that use the annotation will list it on their generated documentation page. Without @Documented
, it's not possible to see which classes use the annotation in the documentation.
The @Inherited
meta-annotation is relevant to annotations that are applied to classes. It has no values. Marking an annotation as @Inherited
alters the way that annotation querying works.
Note that only the super-classes are queried: any annotations attached to interfaces in the classes hierarchy will be ignored.
The @Repeatable
meta-annotation was added in Java 8. It indicates that multiple instances of the annotation can be attached to the annotation's target. This meta-annotation has no values.