Java Standard Meta-Annotations
Meta-annotations are responsible for annotating other annotations. In Java, four standard meta-annotation types—@Target, @Retention, @Documented, and @Inherited—are defined to specify different aspects of an annotation's behavior.
(1) @Target
The @Target annotation specifies the scope or elements that can be annotated by a given annotation type. Annotations may apply to packages, types (classes, interfaces, enums, annotation types), type members (methods, constructors, fields, enum constants), method parameters, and local variables (loop variables, catch block parameters, etc.). By using target in the declaration of an annotation type, its intended target is made explicit. The specific values for target are listed below:
| Name | Target Elements |
|---|---|
| TYPE | Used to describe classes, interfaces (including annotation types), or enum declarations |
| FIELD | Used to describe fields |
| METHOD | Used to describe methods |
| PARAMETER | Used to describe parameters |
| CONSTRUCTOR | Used to describe constructors |
| LOCAL_VARIABLE | Used to describe local variables |
| ANNOTATION_TYPE | Used to declare an annotation type itself |
| PACKAGE | Used to describe packages |
| TYPE_PARAMETER | Used for the declaration of a generic type parameter (note: in modern Java, @Target(ElementType.TYPE_PARAMETER) is used) |
| TYPE_USE | Can be applied to any named element or annotation target name |
(2) @Retention
The @Retention annotation defines at what level an annotation will remain effective. Specifically, it determines whether the described annotation remains in effect during compilation and class loading, execution time reflection, or both. There are three possible values:
- CLASS: The annotation is retained only within the
.classfile (i.e., visible tojavap, but not accessible via runtime reflection). - RUNTIME: The annotation remains effective at run-time and can be accessed using Java Reflection API.
(3) @Documented
The @Documented meta-annotation indicates that the annotated type should be included in Javadoc documentation generated by tools like JDKDoc or EclipseHelp. Consequently, if an element is annotated with this marker, it will appear in the class's tool-generated documentation.
(4) @Inherited
@Inherited is a special annotation used to indicate that a specific type can be inherited and re-used for subclasses of its parent types. If an AnnotationType marked with @Inherited is applied to a superclass, then the same annotation will automatically apply to all direct and indirect subclasses unless overridden by another non-inherited annotation on the subclass itself.