JAVA Annotations
JAVA Annotations
JAVA Introduced annotations in the release of 5. To make anything behave as annotation mainly we have about 3 interfaces documented, Retention and target.
Documented :
Documented is an interface where if any interface acts as annotation it should annotate with @Documented and it should use @interface for annotation. The documentation interface does not contain any methods but it is not a marker interface as it is used as a meta-annotation. It’s applied to other annotations and should be documented by tools such as Javadoc.
Retention :
Retention indicates how long annotations with an annotated interface are to be retained. The default behavior of retention is CLASS. We have to annotate with @Retention and send the arguments to the method value of an ENUM, RetentionPolicy.
RetentionPolicy is an Enum that contains 3 constants RUNTIME, CLASS, and SOURCE.
RUNTIME: These annotations are to be recorded in the class file by the compiler and retained by the VM at run time.
CLASS: These annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.
SOURCE: Annotations are to be discarded by the compiler.
Target :
Indicates the context in which the annotation is applicable. If an @Target is not present on an annotation interface T, then an annotation of type T may be written as a modifier for any declaration.
@Target has one method which returns an array of ElementType enums values.
ElementType is an Enum used to pass values in @Target it contains many values given below :
TYPE: class, interface, enum, or record declaration
FIELD: Field declaration
METHOD: Method declaration
PARAMETER: Formal parameter declaration
CONSTURCTOR : Constructor declaration
LOCAL_VARAIBLE: local variable declaration
ANNOTATION_TYPE: Annotation interface declaration
PACKAGE: Package declaration
TYPE_PARAMETER. : Type Parameter Declaration
TYPE_USE: use of type
MODULE: Module declaration
RECORD_COMPONENT: Record component
The array of ElementType passing in @Target should not repeat the same constant otherwise Java will give compile time error.
JAVA Provides many annotations like FunctionalInterface which is an informative annotation that does not contain any method.
Like below
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
Public @interface FunctionalInterface {
}
Comments
Post a Comment