Android 进阶之注解annotation 的使用

什么是注解

在写代码的时候,经常会看到@Override @Deprecated @SuppressWarnings等,这些就是注解

就咱们看看官方的解释

An annotation is a form of metadata, that can be added to Java source code.
 Classes, methods, variables, parameters and packages may be annotated. 
Annotations have no direct effect on the operation of the code they annotate.

注释是元数据的一种形式,可以添加到java源代码中。
类、方法、变量、参数和包可以被注释。
注释对它们注释的代码的操作没有直接影响。

从官方解释中我们可以明确一点,注解就是注解对代码没有直接的影响,只是一个标记而已

元注解

我们先看看@Override 的代码

/**
 * Indicates that a method declaration is intended to override a
 * method declaration in a supertype. If a method is annotated with
 * this annotation type compilers are required to generate an error
 * message unless at least one of the following conditions hold:
 *
 * <ul><li>
 * The method does override or implement a method declared in a
 * supertype.
 * </li><li>
 * The method has a signature that is override-equivalent to that of
 * any public method declared in {@linkplain Object}.
 * </li></ul>
 *
 * @author  Peter von der Ah&eacute;
 * @author  Joshua Bloch
 * @jls 9.6.1.4 @Override
 * @since 1.5
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

我们可以看到Override 上面有两个注解这就是元注解
元注解就是用来定义注解(@interface)的注解,作用就是定义注解的使用范围,作用域等等

元注解的类型

元注解共有四种@Retention @Target @Inherited @Documented

1.@Retention

保留的范围,默认值为CLASS. 可选值有三种

public enum RetentionPolicy {
    SOURCE,//只在源码中可用
    CLASS,//在源码和字节码中可用
    RUNTIME;//在源码,字节码,运行时均可用

    private RetentionPolicy() {
    }
}

2.@Target

表示这个注解可以用来作用于哪些程序的元素

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
}

@Inherited

是否可以被继承,默认为false
类继承关系中@Inherited的作用
类继承关系中,子类会继承父类使用的注解中被@Inherited修饰的注解
接口继承关系中@Inherited的作用
接口继承关系中,子接口不会继承父接口中的任何注解,不管父接口中使用的注解有没有被@Inherited修饰
类实现接口关系中@Inherited的作用
类实现接口时不会继承任何接口中定义的注解

@Document

说明该注解将会被包含在javadoc中

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容