Java 元注解

2018-12-12  本文已影响0人  Leero丶

学习Android APT需要我们具备自定义注解以及注解处理器的相关知识,这里简单介绍下Java元注解。注解是在JDK1.5后引入的,包含了4种元注解:@Target @Retention @Documented @Inherited
1. @Target
用于声明注解的作用位置,即使用对象。在下面的 ElementType 枚举中我们可以清楚看到 @Target 所能接受的值以及对应的使用范围。其中需要注意的是TYPE_PARAMETERTYPE_USE是在JDK 1.8后引入的。

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
}

2. @Retention
用于声明注解的保留范围,相当于作用域,即在什么时候可以使用。
SOURCE表示该注解只能保留在源代码中,在编译时会被丢弃,不会在class字节码文件中出现
CLASS表示该注解可以保留在class字节码文件中,即编译时可用
RUNTIME表示该注解可在代码运行时保留,可以通过反射获得

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
}

3. @Documented
表示拥有该注解的元素可以被 javadoc 这类的工具文档化。

4.@Inherited
表示允许子类继承父类中的注解。

上一篇 下一篇

猜你喜欢

热点阅读