一
例1:
1 @Target({ElementType.FIELD, ElementType.METHOD})//可以运用到字段及方法上 2 @Retention(RetentionPolicy.RUNTIME) 3 @Constraint(validatedBy = ThresholdValidator.class) 4 @Documented 5 public @interface Threshold { 6 7 String regexp(); 8 9 String message() default ""; 10 11 Class<?>[] groups() default {}; 12 13 Class<? extends Payload>[] payload() default {}; 14 15 }
@Target: 是指定义的注解可以应用在哪些程序上面
看一下ElementType 的源码
1 public enum ElementType { 2 /** Class, interface (including annotation type), or enum declaration */ 3 TYPE, 4 5 /** Field declaration (includes enum constants) */ 6 FIELD, 7 8 /** Method declaration */ 9 METHOD, 10 11 /** Parameter declaration */ 12 PARAMETER, 13 14 /** Constructor declaration */ 15 CONSTRUCTOR, 16 17 /** Local variable declaration */ 18 LOCAL_VARIABLE, 19 20 /** Annotation type declaration */ 21 ANNOTATION_TYPE, 22 23 /** Package declaration */ 24 PACKAGE
@Retention: 是指java编译期如何对待注解的
看下RetentionPolicy的源码
1 public enum RetentionPolicy { 2 /** 3 * Annotations are to be discarded by the compiler. 4 *注释会在编译期丢弃 5 */ 6 SOURCE, 7 8 /** 9 * Annotations are to be recorded in the class file by the compiler 10 * but need not be retained by the VM at run time. This is the default 11 * behavior. 12 * 注释会在编译期保留在class中但是会被jvm忽视 13 */ 14 CLASS, 15 16 /** 17 * Annotations are to be recorded in the class file by the compiler and 18 * retained by the VM at run time, so they may be read reflectively. 19 * 20 * @see java.lang.reflect.AnnotatedElement 21 * 注释会保留在class中而且也会被jvm读取 22 */ 23 RUNTIME 24 }
@Documented
指被定义的注解被认作为所熟悉的程序单元的公开API之一,会在javadoc中显示