一、注解位置:
@Target隶属于java本身带有的注解,位置在jdk的rt.jar包中
二、相关源码:
@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 */
/** 若为type类型,可以修饰类、接口(包括注解类型)或者枚举 */
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
}
四、使用举例:
@Target(ElementType.TYPE_PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface TypeParameterAnnotation {
}
// 如下是该注解的使用例子
public class TypeParameterClass<@TypeParameterAnnotation T> {
public <@TypeParameterAnnotation U> T foo(T t) {
return null;
}
}
实现了一个自定义注解@TypeParameterAnnotation(注解的实际作用当前例子不展开,只体现使用方法和使用位置) ,并用@Target(ElementType.TYPE_PARAMETER)进行修饰,表示此注解可以用来修饰类型参数
下面在TypeParameterClass类中,使用@TypeParameterAnnotation对参数进行修饰