@Inherited meta-annotation
The @Inherited meta-annotation can be used to annotate any annotation, but when the annotation is used, it only gets inherited by a subclass of a class that is annotated by the inherited annotation. In the Java Code, create another class.
The name of this class is
public class CustomProcessor extends AbstractProcessor {
We want to create some Annotations in a new class.
meta annotation of Retention and RetentionPolicy.RUNTIME
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface InheritedClassAnnotation { }
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@interface InheritedInterfaceAnnotation { }
Create a new class called InheritedAnnotationExample.
You have to be at the following path before you execute the command.
D:\AnnotationsProject\out\production\AnnotationsProject>
// Command to execute
javac -d . -cp . -processor CustomProcessor ../../../src/InheritedAnnotationExample.java
// This is the output of the program
InheritedClassAnnotation
CLASS : SuperClass
CLASS : InheritedAnnotationExample
InheritedInterfaceAnnotation
INTERFACE : SuperInterface
D:\AnnotationsProject\out\production\AnnotationsProject>
I didn't specify Target Type for either of these annotations.
An Annotation that has not been Annotated with the meta-annotation Target, can be applied to most types but not all.
The target types are:
PACKAGE, MODULE, ANNOTATION_TYPE, CONSTRUCTOR,
FIELD, LOCAL_VARIABLE, METHOD, PARAMETER, TYPE, TYPE_PARAMETER, and TYPE_USE.
Go back to code. Add additional annotations to the Custom Annotation Source File.
// Intended for Type Parameter
@Target(ElementType.TYPE_PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@interface TypeParameterAnnotation { }
// Intended for Type Use
@Target(ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
@interface TypeUseAnnotation { }
Add another class called
public class AnnotateEverythingExample {
The class is attempting to Annotate everything with the exclusion of module and package.
All of the Annotations that I have declared in the CustomAnnotations file.
Annotations can be applied almost anywhere, but there are 3 exceptions.
We need these types to be specified before they can be used.
Let us do this at the Annotation Level. Go back to the CustomAnnotation Source file.
Retention only
The Type Annotation has retention only.
D:\AnnotationsProject\out\production\AnnotationsProject>javac -d . -cp . -processor CustomProcessor ../../../src/AnnotateEverythingExample.java
AttributeAnnotation
FIELD: AnnotateEverythingExample.aField
TypeAnnotation
CLASS: AnnotateEverythingExample
ConstructorAnnotation
CONSTRUCTOR: AnnotateEverythingExample.AnnotateEverythingExample()
TypeParameterAnnotation
TYPE_PARAMETER: <T>getSomething(T).T
MethodParameterAnnotation
PARAMETER: doSomething(java.lang.String).s
MethodAnnotation
METHOD: AnnotateEverythingExample.doSomething(java.lang.String)
D:\AnnotationsProject\out\production\AnnotationsProject>