文章目录
一、元注解定义
注解可以描述为元数据,即一种描述数据的数据。所以,可以说注解就是源代码的元数据。
所谓元注解其主要作⽤就是负责注解其他注解,为其他注解提供了相关的解释说明。
Java中常用的元注解有@Target、@Retention 、@Documented、@Inherited和@Repeatable。
二、元注解的使用
@Target:用于指定注解的使用范围或目标
ElementType.TYPE:类、接⼝、注解、枚举
ElementType.FIELD:字段、枚举常量
ElementType.METHOD:⽅法
ElementType.PARAMETER:形式参数
ElementType.CONSTRUCTOR:构造⽅法
ElementType.LOCAL_VARIABLE:局部变量
ElementType.ANNOTATION_TYPE:注解
ElementType.PACKAGE:包
ElementType.TYPE_PARAMETER:类型参数
ElementType.TYPE_USE:类型使⽤
@Retention:用于指定注解的生命周期
⽤于指定注解的保留策略
RetentionPolicy.SOURCE:注解只保留在源码中,在编译时会被编译器丢弃
RetentionPolicy.CLASS:(默认的保留策略) 注解会被保留在Class⽂件中,但不会被加载到虚拟机中,运⾏时⽆法获得
RetentionPolicy.RUNTIME:注解会被保留在Class⽂件中,且会被加载到虚拟机中,可以在运⾏时获得
@Documented:⽤于将注解包含在javadoc中
默认情况下,javadoc是不包括注解的,但如果使⽤了@Documented注解,则相关注解类型信息会被包含在⽣成的⽂档中;Documented是一个标记注解,没有成员。
@Inherited:用于指明父类注解会被子类继承得到
该注解是一个标记注解,阐述了某个被标注的类型是被继承的
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ParentAnnotation {
String key();
String value();
}
@ParentAnnotation(key ="key", value ="value")
publicclass Parent {
}
publicclass Son extends Parent {
publicstaticvoidmain(String[] args){
Annotation[] annotations = Son.class.getAnnotations();
// [@com.ParentAnnotation(key=key, value=value)]
System.out.println(Arrays.toString(annotations));
}
}
@Repeatable:用于声明标记的注解为可重复类型注解,可以在同⼀个地方多次使用
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(RepeatableAnnotation.class)
public @interface TestAnnotation {
String key();
String value();
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface RepeatableAnnotation {
TestAnnotation[]value();
}
@TestAnnotation(key ="key1", value ="value1")
@TestAnnotation(key ="key2", value ="value2")
publicclass Test {
publicstaticvoidmain(String[] args){
RepeatableAnnotation annotation = Test.class.getAnnotation(RepeatableAnnotation.class);
TestAnnotation[] testAnnotations = annotation.value();
for(TestAnnotation testAnnotation : testAnnotations){
// @com.TestAnnotation(key=key1, value=value1)
// @com.TestAnnotation(key=key2, value=value2)
System.out.println(testAnnotation);
}
}
}
参考:
Java-五种元注解详解