什么是元注解?
元注解:修饰自定义注解的常用元注解。
@Target、@Retention 、@Documented、@Inherited和@Repeatable是Java语言中用于修饰自定义注解的常用元注解,其中@Repeatable 是JDK8.0新添加的元注解。
@Target:
用于指定被修饰的自定义注解只能用于修饰程序中哪些元素,该元注解有如下属性值:
- ElementType.ANNOTATION_TYPE:应用于其他注解的元注解
- ElementType.CONSTRUCTOR:应用于构造函数
- ElementType.FIELD:应用于全局属性
- ElementType.LOCAL_VARIABLE:应用于方法中的本地变量
- ElementType.METHOD:应用于方法
- ElementType.PACKAGE:应用于包
- ElementType.PARAMETER:应用于方法的参数
- ElementType.TYPE:应用于类、接口或者枚举声明
package venus;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
public @interface Autowired {
String[] value() default "";
}
package venus;
@Autowired()//错误,@Target属性值为ElementType.FIELD,故该注解只能修饰该类中成员变量。
public class Test {
@Autowired()
private String name;
}
@Retention:
用于指定被修饰的自定义注解可以保留多久,该元注解有如下属性值:
- RetentionPolicy.SOURCE:编译器将直接丢弃被修饰的注解。
- RetentionPolicy.CLASS:默认值,编译器将把注解记录在class文件中,当运行Java程序时,虚拟机不再保留注解;
- RetentionPolicy.RUNTIME:编译器将把注解记录在class文件中,当运行java程序时,虚拟机保留注解,程序可以通过反射获取该注解;
package venus;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.CLASS)
public @interface Autowired {
String[] value() default "";
}
package venus;
import java.lang.reflect.Field;
public class Test {
@Autowired()
private String name;
public static void main(String[] args) {
Class clazz = Test.class;
try {
Field field= clazz.getDeclaredField("name");
Autowired autowired = field.getAnnotation(Autowired.class);
System.out.println(autowired);//输出为null,因为@Retention属性值为RetentionPolicy.CLASS,在运行时不会保留在Java虚拟机中;若@Retention属性值为RetentionPolicy.RUNTIME,则结果为@venus.Autowired(value=[])
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
@Documented:
执行javadoc命令时,被该元注解修饰的自定义注解也会生成在文档中
@Inherited:
如果父类所使用的注解有@Inherited修饰,则子类可以继承该注解,否则不能继承。
@Repeatable:
所修饰的自定义注解可以重复在同一类、方法或变量上使用。