Think in java笔记: Annotation
Annotation是什么?
Annotation是一种元数据信息,很奇怪的想起来了AspectJ的AOP,就是在方法、package等元素上加上一些标记,然后再自定负责自己的annotation,实现功能。和interface差不多,但是可以有默认值。如何定义一个annotation
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Test { }
定义annotation还需要meta-annotation:
@target
和@Retention
@target
:定义在哪使用这个annotation(比如说成员变量或方法)@Rentention
:定义什么时候可用,SOURCE 还是CLASS, 还是RUNTIME。
这样不包含任何element的annotation,被称为marker annotation.
Meta-annotations
name Description @Target 可以使用的ElementType类中的变量 @Rentention annotation信息保留多久,具体的类在RetentionPolicy @Documented 在javadocs中包含此annotation的信息 @Inherited 允许所有子类继承它们的父annotation annotation processors(annotation执行)
如果没有工具来读取annotation,annotations几乎就和评论就一样。一个重要的部分就是创建和使用annotation processors. Java提供了反射的方法来实现annotation processors.还提供了apt用来解析source code.public class UseCaseTracker { public static void trackUseCases(List<Integer> useCases, Class<?> cl){ for(Method m : cl.getDeclaredMethods()){ UseCase uc = m.getAnnotation(UseCase.class); if(uc != null){ 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); } } public static void main(String[] args) { List<Integer> useCases = new ArrayList<Integer>(); Collections.addAll(useCases, 47, 48, 49, 50); trackUseCases(useCases, PasswordUtils.class); } }
Annotation Value限制
- compiler对value有限制要求的。没有任何Element可以拥有一个没有指定的value。这意味着elements元素必须拥有默认值或者使用的时候赋值。
- 任何基本类型必须赋值,不能使用null。意味着defaut或者赋值的时候,就必须使用一个确定的值。