@Target注解详解

一、注解位置:

@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对参数进行修饰

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值