元注解
version:1.8
元注解:即注解的注解。
java.lang.annotation包定义了一些最基础的元注解。
@Target
@Retention
@Documented
@Inherited
1.8之后多了
@Repeatable //重复注解
@Native不为元注解
@Target
注解的目标:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}
ElementType是一个枚举类。
可使用的参数:
@Target(ElementType.TYPE) //接口、类、枚举
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR) //构造函数
@Target(ElementType.FIELD) //字段、枚举的常量
@Target(ElementType.LOCAL_VARIABLE) //局部变量
@Target(ElementType.ANNOTATION_TYPE) //注解
@Target(ElementType.PACKAGE) //包
1.8 版本后又多了两个
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
TYPE_PARAMETER 主要用于泛型的类型参数
TYPE_USE 可用于任何使用类型的地方,包括泛型的类型参数,字段等。
@Retention
注解的保留位置:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
/**
* Returns the retention policy.
* @return the retention policy
*/
RetentionPolicy value();
}
RetentionPolicy 同样为枚举类
public enum RetentionPolicy {
//注解仅存在于源码中,在class字节码文件中不包含
SOURCE,
//注解会在class字节码文件中存在,但运行时无法获得
CLASS,
//注解会在class字节码文件中存在,在运行时可以通过反射获取到
RUNTIME
}
@Documented
将此注解包含在 javadoc 中
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}
@Inherited
将带有@Inherited的注解使用在A类上,则其子类自动继承该注解。
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}
@Repeatable
顾名思义,使得一个注解可以重复使用,其参数为重复的注解存储的位置。
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Repeatable {
/**
* Indicates the <em>containing annotation type</em> for the
* repeatable annotation type.
* @return the containing annotation type
*/
Class<? extends Annotation> value();
}
使用示例:
public @interface Numbers {
Number[] value();
}
@Repeatable(Numbers.class)
public @interface Number {
String number();
}
public class Test {
@Number(number = "1")
@Number(number = "2")
public String toString(){
return "numbers";
}
}
@Native
表示这个变量可以被本地代码引用。
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE)
public @interface Native {
}
注意其作用在字段上(不为元注解),且仅保留在源码中。
常常被代码生成工具使用。