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 | @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation
CONSTRUCTOR | constructors | @MyAnnotationpublic MyClass() {} |
FIELD | fields, enum constants | @XmlAttributeprivate int count; |
LOCAL_VARIABLE | variable declarations inside methods| for (@LoopVariable int i = 0; i < 100; i++) { @Unused String resultVariable;} |
PACKAGE | package (in package-info.java
) | @Deprecatedpackage very.old; |
METHOD | methods | @XmlElementpublic int getCount() {…} |
PARAMETER | method/constructor parameters | public Rectangle( @NamedArg(“width”) double width, @NamedArg(“height”) double height) { …} |
TYPE | classes, interfaces, enums | @XmlRootElementpublic class Report {} |
ElementType | target | example usage on target element | — | — | — | TYPE_PARAMETER | Type parameter declarations | public <@MyAnnotation T> void f(T t) {} | TYPE_USE | Use of a type | Object o = “42”;String s = (@MyAnnotation String) o; |
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.