Java Annotation
What is an annotation?
Annotation is metadata and metadata is a set of data that gives information about other data. Annotations are essentially just information about your code.
How to Create Custom Annotation?
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Status {
String author();
int completion() default 0;
}
@Target: Specifies where annotation can be placed. If you don’t specify this, the annotation can be placed anywhere, Here are some valid targets.
ElementType.TYPE(class, interface, enum)
ElementType.FIELD(instance variable)
ElementType.METHOD
ElementType.PARAMETER
ElementType.CONSTRUCTOR
ElementType.LOCAL_VARIABLE
@Retention defines how long the annotation should be kept around. Here are some valid retention policies
RetentionPolicy.SOURCE
Discard during the compile step. These annotations don’t make any sense after the compilation has been completed, so they don’t need to be turned into bytecode. eg. @Override, @SuppressWarning
RetentionPolicy.CLASS
Discard during the class load. Useful when doing bytecode-level post-processing. Somewhat surprisingly, this is the default.
RetentionPolicy.RUNTIME
Don’t discard, This annotation should be available for reflection at runtime.