基本定义
元注解用于修饰其他Annotation定义
4个标准的meta-annotaion类型:
1、Retention
2、Target
3、Documented
4、Inherited
自定义注解一般都会使用Retention和Target,其余两个不太常用。
Retention
指定该Annotation的声明周期:SOURCE、CLASS(默认行为)、RUNTIME
只有声明为RUNTIME的声明周期的注解,才能通过反射获取。
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler. 编译时就会被销毁
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior. 编译时有,内存无
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
使用实例:
@Target({TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
String[] value();
}
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();
}
可以使用的元素
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
Documented:
用户指定被该元Annotation修饰的Annotation类江北javadoc工具提成文档。默认情况下,javadoc信息不包括注解。
定义为Documented的注解,必须设置Retention值为RUNTIME
Inherited
被它修饰的Annotation具有继承性。即如果某个类使用类@Inherited修饰的Annotation,则它的子类自动具有该注解。