Annotation 注解,是代码里做的特殊标记,可以在编译,类加载,运行时在不改变原有逻辑的情况下,被读取,并执行相应的处理,通过使用Annotation,程序员可以在源文件中嵌入一些补充的信息。代码分析工具,开发工具和部署工具可以通过这些补充信息进行验证或者进行部署。Annotation类似于修饰符一样被使用,可以用于包,类,构造方法,方法,成员变量,参数,局部变量的声明。
Annotation是一个接口
三个步骤:
编写注解在类上应用注解对应用了注解的类进行反射操作的类语法:
访问控制权限 @interface Annotation 名称{}
如:
public @interface MyAnnotation{}
在Annotation中定义变量
public @interface MyAnnotation{ public String name(); public String info(); }定义变量后,调用此Annotation时必须设置变量值
@MyAnnotation(name="vince",info="hello") public class Demo{ }通过default指定变量默认值,有了默认值,在使用Annotation时可以不设值
public @interface MyAnnotation{ public String name() default "vince"; }定义一个变量的数组,接收一组参数
public @interface MyAnnotation{ public String[] name(); } @MyAnnotation(name={"java","cc"}) public class Demo{}使用枚举变量限制取值范围
public enum Color{ RED,GREEn,BLUE } public @interface MyAnnotation{ public Color color(); }Annotation想要决定其作用范围,通过@Retention指定,而Retention指定的范围,由RetentionPolicy决定,RetentionPolicy指定了三种范围:
范围描述public static final RetentionPolicy SOURCE在java源程序中存在public static final RetentionPolicy CLASS在java生成的class中存在public static final RetentionPolicy RUNTIME在java运行的时候存在 @Retention(Value = RetentionPolicy.RUNTIME) public @interface MyAnnotation{ public String name(); }一个Annotation真正起作用,必须结合反射机制,在反射中提供了以下的操作方法:
java.lang.reflect.AccessibleObject
方法描述public boolean isAnnotationPresent(Class<? extend Annotation > annotationClass)判断是否是指定的Annotation,仅限JVM虚拟机使用。public Annotation[] getAnnotations()得到全部的Annotation#6.@Documented注解
此注解表示的是文档化,可以在生成doc文档的时候添加注解
@Documented @Retention(value = RetentionPolicy.RUNTIME) public @interface MyAnnotation{ public String name(); public String info(); } 可以增加一些DOC注解 /** * xxxxdoc */ @MyAnnotation(name="vince",info="xx") public String toString(){ return "hello"; }@Target注解表示的是一个Annotation的使用范围
范围描述public static final ElementType TYPE只能在类或接口或枚举上使用public static final ElementType FIELD在成员变量使用public static final ElementType METHOD在方法中使用public static final ElementType PARAMETER在参数上使用public static final ElementType CONSTRUCTOR在构造中使用public static final ElementType LOCAL_VARIABLE在局部变量上使用public static final ElementType ANNOTATION_TYPE只能在Annotation中使用public static final ElementType PACKAGE只能在包中使用@Inherited表示一个Annotation是否允许被其子类继承下来。
@Inherited @Target(value=ElementType.TYPE) @Retention(value=RetentionPolicy.RUNTIME) public @interface MyAnnotation{ public String name(): }使用时允许被其子类继承。
菜鸟教程