1.阅读源码时经常会有一些注解,通常是为了更加灵活的设计。代码片段一选自Netty源码:
@Inherited @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface Sharable { // no value }
Inherited应用在类上,继承的子类会自动向上查找父类是否存在该注解。
@Sharable public class Animal { }
public class Dog extends Animal { }
测试一下:
public class MyTest { public static void main(String[] args) { boolean annotation = Dog.class.isAnnotationPresent(Sharable.class); System.out.print(annotation); } }
Documented主要用于注释,成为公共API一部分
Retention 源码:
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Retention { /** * Returns the retention policy. * @return the retention policy */ RetentionPolicy value(); }
这个注解主要需要返回一个值,值如下:
public enum RetentionPolicy { /** * Annotations are to be discarded by the compiler. 注释被编译器丢弃 */ SOURCE, /** * Annotations are to be recorded in the class file by the compiler * but need not be retained by the VM at run time. This is the default * behavior. 注释由编译器记录在类文件中,但不需要运行时被VM保留。这是一个默认的动作。 */ CLASS, /** * Annotations are to be recorded in the class file by the compiler and * retained by the VM at run time, so they may be read reflectively. *可以被被编译器和运行时保留,能够被反射读到 * @see java.lang.reflect.AnnotatedElement */ RUNTIME }
Target源码:
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Target { /** * Returns an array of the kinds of elements an annotation type * can be applied to. * @return an array of the kinds of elements an annotation type * can be applied to 返回可用注解的各种各样类型的数组。 */ ElementType[] value(); } 主要有以下几种 public enum ElementType { /** Class, interface (including annotation type), or enum declaration */ 类,接口(包含注解类型)枚举声明 TYPE, /** Field declaration (includes enum constants) */ 字段声明(包含枚举常量) FIELD, /** Method declaration */ 方法声明 METHOD, /** Formal parameter declaration */ 正式参数声明 PARAMETER, /** Constructor declaration */ 构造声明 CONSTRUCTOR, /** Local variable declaration */ 本地值声明 LOCAL_VARIABLE, /** Annotation type declaration */ 注解类型声明 ANNOTATION_TYPE, /** Package declaration */ 包声明 PACKAGE, /** * Type parameter declaration * * @since 1.8 */ 类型参数声明 TYPE_PARAMETER, /** * Use of a type * * @since 1.8 */ 类型使用 TYPE_USE }