Java元注解

来源:互联网 发布:手机淘宝售后服务流程 编辑:程序博客网 时间:2024/04/29 20:41

1.何为元注解?

元注解(meta-annotation)就是注解的注解。

2.有哪些元注解?

Java有四个元注解 @Retention @Target @Document @Inherited;

@Retention

表示注解被保留的程度:源码,CLASS文件,运行时。

需要配合注释修饰符RetentionPolicy使用。

源码:

package java.lang.annotation;/** * @since 1.5 */@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Retention {    RetentionPolicy value();}

@Target 

注解的合法作用对象,需要结合修饰符ElementType来使用。

例如Element.METHOD修饰的注解,就只能用在方法上,如果用在了类上,就会报错。

所以我们看到四个元注解的Target都是@Target(ElementType.ANNOTATION_TYPE),表示作用在注解上。

源码:

package java.lang.annotation;@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Target {    ElementType[] value();}


@Document

表示被注解的内容会出现在javadoc中,即javadoc中会包含该注解。

源码:

package java.lang.annotation;/**  * @author  Joshua Bloch * @since 1.5 */@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Documented {}


@Inherited

表示子类可以继承父类中的该注解(该注解是注解于父类)

源码:

package java.lang.annotation;@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Inherited {}

3.注解修饰符


在上面的四个元注解中,存在两个注解修饰元素。RetentionPolicy和ElementType

RetentionPolicy:指的是注解的保留程度。

@Retention(RetentionPolicy.SOURCE) //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS)   //默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得
@Retention(RetentionPolicy.RUNTIME)// 注解会在class字节码文件中存在,在运行时可以通过反射获取到

ElementType:指的是注解的作用目标。

@Target(ElementType.TYPE)   //接口、类、枚举、注解
@Target(ElementType.FIELD)  //字段、枚举的常量
@Target(ElementType.METHOD)  //方法
@Target(ElementType.PARAMETER)  //方法参数
@Target(ElementType.CONSTRUCTOR)   //构造函数
@Target(ElementType.LOCAL_VARIABLE) //局部变量
@Target(ElementType.ANNOTATION_TYPE) //注解
@Target(ElementType.PACKAGE)  //




0 0