@Target 、@Retention 、@Documented注解说明

前言

在看源码的时候 经常会看到这三个注解,那么他们都是什么意思呢?

样例

来自override注解的源码

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {

}

@Target 作用 用于指定修饰的类型范围

首先可以看到 注解@override上 标注了两个注解 @Target(ElementType.METHOD) 和 @Retention(RetentionPolicy.SOURCE)

这两个取值分别都是什么意思呢?我们看一下源码

首先是 枚举类 ElementType

可以看到里面包含了一些属性咱们分别说明一下。

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
}

@Target(ElementType.TYPE)  注解的作用目标 - 类、接口、枚举

@Target(ElementType.FIELD)  注解的作用目标 - 字段、枚举常量

@Target(ElementType.METHOD)  注解的作用目标 - 方法

@Target(ElementType.PARAMETER)  注解的作用目标 - 方法参数

@Target(ElementType.CONSTRUCTOR)  注解的作用目标 - 构造方法

@Target(ElementType.LOCAL_VARIABLE)  注解的作用目标 - 局部变量

@Target(ElementType.ANNOTATION_TYPE)  注解的作用目标 - 注解

@Target(ElementType.PACKGE)  注解的作用目标 - 包

@Retention 表示注解的生存周期

先看一下其中参数的源码.

一共包含三个参数

意思分别是

@Retention(RetentionRolicy.SOURCE) 表示 源码级别保留 编译完就销毁,在编译好的class文件中不包含

@Retention(RetentionRolicy.CLASS) 表示 编译级别保留 编译后存在在 class文件中,在jvm运行时丢弃

@Retention(RetentionRolicy.RUNTIME) 表示 运行级别保留 和JVM一起加载 一直被保留,可以被反射调用

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

@Documented 表示包含在javadoc文档中

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值