Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.
Annotations are special interface type. It instructs the java compiler to do something .When Java source code is compiled, annotations can be processed by compiler plug-ins called annotation processors. Annotation processor (annotation processing tool, called
apt
) can read a Java program and take actions based on its annotations.
Java provides three simple annotations and four meta-annotations.
Simple annotations (Annotations applied to java code):
- @Override – this annotation informs the compiler that the method is meant to override the a method declared in super class. It checks that the method is an override method or not. It causes a compile warning if the function is not found in one of the parent classes.
- @Deprecated - annotation indicates that the marked element is deprecated and should no longer be used. It generates a compile warning if the function is used.
- @SuppressWarnings - Instructs the compiler to suppress the compile time warnings specified in the annotation parameters
Meta-annotations (Annotations applied to other annotations):
- @Retention - Specifies how the marked annotation is stored -- Whether in code only, compiled into the class, or available at runtime through reflection.
RetentionPolicy.CLASS: Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time. This is the default behavior.
RetentionPolicy.RUNTIME: Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.
RetentionPolicy.SOURCE: Annotations are to be discarded by the compiler.
- @Documented - Marks another annotation for inclusion in the documentation.
- @Target - Marks another annotation to restrict what kind of java elements the annotation may be applied to
- @Inherited - Marks another annotation to be inherited to subclasses of annotated class (by default annotations are not inherited to subclasses).
Example :
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
public @interface Authorization {
AuthActions[] actions();
public enum AuthActions{
READ,WRITE;
}
}
No comments:
Post a Comment