美文网首页android进阶Android知识Android开发
Java注解——Retention 与 Target

Java注解——Retention 与 Target

作者: wenld_ | 来源:发表于2017-03-23 10:34 被阅读1315次

一、概念

Annontation是Java5开始引入的新特征。中文名称一般叫注解。它提供了一种安全的类似注释的机制,用来将任何的信息或元数据(metadata)与程序元素(类、方法、成员变量等)进行关联。
  更通俗的意思是为程序的元素(类、方法、成员变量)加上更直观更明了的说明,这些说明信息是与程序的业务逻辑无关,并且是供指定的工具或框架使用的。
Annontation像一种修饰符一样,应用于包、类型、构造方法、方法、成员变量、参数及本地变量的声明语句中。

这边只了解一下 Retention 与 Target

二 、使用

@Retention(保留)

告知编译程序如何处理

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
    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中,缺省
     */
    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.
     * 编译程序处理完注解信息后存储在class中,可由VM读入
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

SOURCE 例子:
SuppressWarning 作用是在编译时抑制警告,不必写入到class中

@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {...}

CLASS 例子:
butterknife 框架
编译时将注解写入class文件中。


---- RUNTIME 例子:

@Target(元元素)

表示注释类型的程序元素的种类

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
    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
     * @hide 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     * @hide 1.8
     */
    TYPE_USE
}

相关文章

网友评论

  • 孤独蓝天:文章不完整啊,butterknife 框架
    编译时将注解写入class文件中。并且点击的时候响应,所以加载如JVM
    孤独蓝天:@wenld_ 恩恩,谢谢
    wenld_:@孤独蓝天 :smile: 这篇文章其实只是一个大概的笔记,非常感谢你能仔细阅读:+1::+1::+1:;关于 butteeknife ,只有在bind的时候才用到一次运行时注解, 点击事件 代码在编译时写好了。

本文标题:Java注解——Retention 与 Target

本文链接:https://www.haomeiwen.com/subject/uxkznttx.html