自定义注解基本用法
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Test {
}
自定义注解要关心的点是注解的作用域,和注解类型保留的生命周期
下面来看下@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
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
/** 用于描述类、接口(包括注解类型)或enum声明*/
TYPE,
/** Field declaration (includes enum constants) */
/** 用于描述域 (包括enum常量)*/
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
}
下面看下@Retention注解
@Retention定义了该Annotation被保留的时间长短:
1.某些Annotation仅出现在源代码中,而被编译器丢弃;
2.另一些却被编译在class文件中,注解保留在class文件中,在加载到JVM虚拟机时丢弃,这是默认行为,所以没有用Retention注解的注解,都会采用这种策略
3.而另一些在class被装载时将被读取,注解保留在程序运行期间,此时可以通过反射获得定义在某个类上的所有注解
作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)
取值(RetentionPoicy)有:
1.SOURCE:在源文件中有效(即源文件保留)
2.CLASS:在class文件中有效(即class保留)
3.RUNTIME:在运行时有效(即运行时保留)