4 Annotations Used When Writing Annotations

@Annotation

Description

@Document

whether to put the annotation in Javadocs

@Retention

when the annotation is needed:

  • RetentionPolicy.SOURCE– discard during the compile. These annotations don’t make any sense after the compilation has been completed, so they aren’t written to the bytecode. Examples:
    • @Override
    • @SuppressWarnings
  • RetentionPolicy.CLASS– discard during class load. Useful when doing bytecode-level post-processing. Somewhat surprisingly, this is the default
  • RetentionPolicy.RUNTIME  – do not discard. The annotation should be available for reflection at runtime. This is what we generally use for our custom annotations

@Target

where the annotation can go:

  • ElementType.TYPE (class, interface, enum)
  • ElementType.FIELD (instance variable)
  • ElementType.METHOD
  • ElementType.PARAMETER
  • ElementType.CONSTRUCTOR
  • ElementType.LOCAL_VARIABLE
  • ElementType.ANNOTATION_TYPE (on another annotation)
  • ElementType.PACKAGE (remember package-info.java)

@Inherited

whether subclasses get the annotation

Custom Java Annotation Example

below is custom @Todo annotation:

package com.marcuschiu.example
 
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface Todo {
	public enum Priority {LOW, MEDIUM, HIGH}
	public enum Status {STARTED, NOT_STARTED}
 
	String author() default "Marcus Chiu";
	Priority priority() default Priority.LOW;
	Status status() default Status.NOT_STARTED;
}

below is an example use of @Todo annotation:

@Todo(
	priority = Todo.priority.HIGH,
	author   = "Marcus Chiu",
	status 	 = Todo.Status.STARTED)
public ClassA {
 
	@Todo(
		priority = Todo.Priority.MEDIUM,
		author = "Marcus Chiu",
		status = Todo.Status.STARTED)
	public void incompleteMethod1() {
		...
	}
}

below is an example consumer of @Todo annotation:

Class classA = ClassA.class;
 
for(Method method : classA.getMethods()) {
 
	Annotation annotation = method.getAnnotation(Todo.class);
	Todo todoAnnotation = (Todo) annotation;
 
	if(todoAnnotation != null) {
		System.out.println("Method Name: " + method.getName());
		System.out.println("Author: "      + todoAnnotation.author());
		System.out.println("Priority: "    + todoAnnotation.priority());
		System.out.println("Status: "      + todoAnnotation.status());
	}
}