谈谈Java中的元注解

元注解可以认为是注解的注解。

(我们在定义注解时,可以通过元注解指定注解的保留策略、作用目标、javadoc包含以及子类继承。)

内置的元注解有4个,具体如下:

1、@Retention

2、@Target

3、@Document

4、@Inherited

一、@Retention:标识注解的保留策略

  1. @Retention(RetentionPolicy.SOURCE)   //注解仅存在于源码中,在class字节码文件中不包含

  2. @Retention(RetentionPolicy.CLASS)     // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,

  3. @Retention(RetentionPolicy.RUNTIME)  // 注解会在class字节码文件中存在,在运行时可以通过反射获取到

  4.  

  • 三个阶段生命周期长度 SOURCE < CLASS < RUNTIME,生命周期长的一定能作用到生命周期短的阶段。

  • 如果需要在RUNTIME阶段动态获取注解,那只能用RUNTIME注解

  • 如果在编译时进行一些预处理操作,就用CLASS注解

  • 如果只是做一些检查性操作,比如@Override 和 @SuppressWarnings,可以选用SOURCE注解。

  • ❤️ 源码如下:

    public @interface Retention {

        /**

         * Returns the retention policy.

         * @return the retention policy

         */

        RetentionPolicy value();

    }

     

    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,

        RUNTIME

    }

二、@Target:定义注解的作用目标

@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.PACKAGE) ///包   

 

源码如下:

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();

}

 

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

}

 

三、@Document:说明该注解将被包含在Javadoc中

用法示例:

@Documented

public @interface check {

}

 

源码:

public @interface Documented {

}

四、@Inherited:说明子类可以继承父类中的该注解

 

用法示例:

@Inherited

public @interface check {

}

 

源码:

public @interface Inherited {

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值