“携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第12天,点击查看活动详情
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface CurDataSource {
String source() default "";
}
涉及到了四种注解:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
解析
@Target 说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。
作用:用于描述注解的使用范围
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE, //类、接口(包括注解类型) 或enum声明
/** 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
}
在Java8中 ElementType 新增两个枚举成员,TYPE_PARAMETER
和 TYPE_USE
,在Java8前注解只能标注在一个声明(如字段、类、方法)上,Java8后,新增的TYPE_PARAMETER
可以用于标注类型参数,而TYPE_USE
则可以用于标注任意类型(不包括class)。
@Retention表示生命周期
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE, //注解只在源代码中存在,编译成class之后,就没了。@Override 就是这种注解。
/**
* 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.
*/
CLASS,//注解在java文件编程成.class文件后,依然存在,但是运行起来后就没了。@Retention的默认值,即当没有显式指定@Retention的时候,就会是这种类型
/**
* 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//注解在运行起来之后依然存在,程序可以通过反射获取这些信息
}
指示注释类型是自动继承的。如果注释类型声明中存在继承的元注释,并且用户在类声明中查询该注释类型,并且该类声明没有该类型的注释,则将自动查询该类的超类以获取注释类型。重复此过程,直到找到该类型的注释,或到达类层次结构(对象)的顶部为止。如果没有超类对此类型进行注释,则查询将指示所讨论的类没有此类注释。请注意,如果带注释的类型用于注释除类之外的任何内容,则此元注释类型无效。还要注意,此元注释仅使注释从超类继承;已实现的接口上的注释无效。
@Inherited表示该注解具有继承性。 即如果一个使用了@Inherited 修饰的annotation 类型被用于一个class,则这个annotation 将被用于该class 的子类。
@Documented 在用javadoc命令生成API文档后,文档里会出现该注解说明