4 Annotations Used When Writing Annotations
|
@Annotation |
Description |
|---|---|
|
|
whether to put the annotation in Javadocs |
|
|
when the annotation is needed:
|
|
|
where the annotation can go:
|
|
|
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());
}
}