先附上原码:
package java.lang.annotation;
/**
* @since 1.5
* @jls 9.6.4.1 @Target
* @jls 9.7.4 Where Annotations May Appear
*/
@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();
}
@Target注解自JDK1.5之后就有了,其作用是定义在注解的上方,表明其注解的作用范围。
例如:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginToken {
boolean required() default true;
}
表示定义的@LoginToken注解可以作用于方法、类、接口、枚举上。
看原码可以知道@Target的取值是一个ElementType的数组,再查看ElementType原码,如下:
package java.lang.annotation;
/**
* @author Joshua Bloch
* @since 1.5
* @jls 9.6.4.1 @Target
* @jls 4.1 The Kinds of Types and Values
*/
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
}
发现ElementType是个枚举。属性作用如下:
TYPE:接口、类、枚举
FIELD:字段、枚举的常量
METHOD:方法
PARAMETER:方法参数
CONSTRUCTOR:构造函数
LOCAL_VARIABLE:局部变量
ANNOTATION_TYPE:注解
PACKAGE:包
@Target的value取值可以是一个,也可以是多个,如果未指定value,表明注解可以作用于任何范围。
本文有参考:https://blog.csdn.net/PERCENTILE__/article/details/104272624
https://www.jianshu.com/p/98c8db436fe4