# what's annotation, why we need annotation?java
- metadata
app
- to combine metadata with source code files.ide
- help to ease the burden of writing boilerplate code.this
# define annotation
spa
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Test {}
@Target : define where you can apply this annotation..net
@Retention: defines where the annotation is available in source code, in class files or at the runtime.rest
- above one has no elements, so it's a marker annotation.
code
# simple annotationip
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface UseCase { // id is type-checked by complier public int id(); public String description() default "no description"; }
# annotation processorci
public class UseCaseTracker { public static void main(String[] args) { List<Integer> useCases = new ArrayList<Integer>(); Collections.addAll(useCases, 47, 48, 49, 50); trackUseCases(useCases, PasswordUtils.class); } private static void trackUseCases(List<Integer> useCases, Class cl) { for (Method method : cl.getDeclaredMethods()) { UseCase uc = method.getAnnotation(UseCase.class); if (null != uc) { System.out.println("Found use case: " + uc.id() + ", " + uc.description()); useCases.remove(new Integer(uc.id())); } } for (int i : useCases) { System.out.println("warning: missing use case: " + i); } } }
# what types of element are allowed in annotation?
- all primitive.
- String
- Class
- enum
- annotation
- 1-dimention array of any of the above.
# what's the restriction using annotation?
- no element can have an unspecified value, all elements must either have default values or values provided by the class that uses the annotation.