该篇主要说明的是java的元注解。
元注解是可以注解到注解上的注解,或者说元注解是一种基本注解,但是它能够应用到其它的注解上面。
元注解有@Documented
、@Retention
、@Target
、@Inherited
、@Repeatable
5 种。
@Documented
说明:
@Documented
注解表明这个注解应该被 javadoc工具记录。 默认情况下,javadoc
是不包括注解的。 但如果声明注解时指定了 @Documented
,则它会被 javadoc
之类的工具处理, 所以注解类型信息也会被包括在生成的文档中。
源码:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}
@Retention
说明:
@Retention
表示该注解的的存活时间。
源码:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
RetentionPolicy value();
}
其中 RetentionPolicy
是一个枚举类,源码如下:
public enum RetentionPolicy {
// 注解只在源码阶段保留,在编译器进行编译时它将被丢弃忽视。
SOURCE,
// 注解只被保留到编译进行的时候,它并不会被加载到 JVM 中
CLASS,
// 注解可以保留到程序运行的时候,它会被加载进入到 JVM 中,所以在程序运行时可以获取到它们。
RUNTIME
}
@Target
说明:
@Target
表示该注解运用的地方。
源码:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
其中 ElementType
是一个枚举类,源码如下:
public enum ElementType {
TYPE,//可以给一个类型进行注解,比如类、接口、枚举
FIELD,//可以给属性进行注解
METHOD,//可以给方法进行注解
PARAMETER,//可以给一个方法内的参数进行注解
CONSTRUCTOR,//可以给构造方法进行注解
LOCAL_VARIABLE,//可以给局部变量进行注解
ANNOTATION_TYPE,// 可以给一个注解进行注解
PACKAGE,//可以给一个包进行注解
TYPE_PARAMETER,// 类型参数上注解,从1.8版本才有
TYPE_USE//使用的类型上
}
@Inherited
说明:
@Inherited
是继承的意思。注解 @A
被 @Inherited
进行注解,如果类 B
被注解 @A
进行注解,类 C
继承了类 B
,则类 C
也拥有注解 @A
。具体查看如下图解源码。
源码:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}
图解源码:
@Inherited
public @interface A {}
@A
class B{}
class C extends B{}
@Repeatable
说明:
@Repeatable
表名该注解修饰的注解的使用是可以重复的。该注解从1.8版本加入。
源码:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Repeatable {
Class<? extends Annotation> value();
}
代码案例如下:
@interface Students {
Student[] value();
}
@Repeatable(Students.class)
@interface Student{
String name default "";
}
@Student(name="zhangsan")
@Student(name="lisi")
@Student(name="wangwu")
public class School{
}