自定义注解@Target和@Retention说明

自定义注解基本用法
 

@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:在运行时有效(即运行时保留)

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值