前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >注解使用入门(一)

注解使用入门(一)

作者头像
程序员徐公
发布2018-09-18 17:31:51
3060
发布2018-09-18 17:31:51
举报

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1342032

为什么要写这一系列的博客呢?

因为在 Android 开发的过程中, 泛型,反射,注解这些知识进场会用到,几乎所有的框架至少都会用到上面的一两种知识,如 Gson 就用到泛型,反射,注解,Retrofit 也用到泛型,反射,注解 。学好这些知识对我们进阶非常重要,尤其是阅读开源框架源码或者自己开发开源框架。

本篇博客要讲解主要分为以下几个问题

  1. 注解的相关知识点
  2. 基于运行时的注解的例子解析说明

至于关于编译时的注解,待下篇博客的时候会结合例子讲解一下,目前我也正在学习当中

注解的相关知识点

提到注解,大多数人应该都不默认,在我们程序中见到的@Override,@Deprected,@SupressWarnings等等,这些都是注解,只不过是系统自己封装好的,而我们平时比较少去深入理解是怎样实现的?

1)什么是注解(Annotation):

Annotation(注解)就是Java提供了一种元程序中的元素关联任何信息和着任何元数据(metadata)的途径和方法。Annotion(注解)是一个接口,程序可以通过反射来获取指定程序元素的Annotion对象,然后通过Annotion对象来获取注解里面的元数据。

2)注解的分类:

根据注解参数的个数,我们可以将注解分为三类:

  1. 标记注解:一个没有成员定义的Annotation类型被称为标记注解。这种Annotation类型仅使用自身的存在与否来为我们提供信息。比如后面的系统注解@Override;
  2. 单值注解
  3. 完整注解 

根据注解使用方法和用途,我们可以将Annotation分为三类:

  1. JDK内置系统注解
  2. 元注解
  3. 自定义注解

3)元注解:

元注解的作用就是负责注解其他注解。Java5.0定义了4个标准的meta-annotation类型,它们被用来提供对其它annotation类型作说明。Java5.0定义的元注解:

  1. @Target
  2. @Retention
  3. @Documented
  4. @Inherited

元注解 解析说明

  • @Documented 是否会保存到 Javadoc 文档中
  • @Retention 保留时间,可选值 SOURCE(源码时),CLASS(编译时),RUNTIME(运行时) 默认为 CLASS,SOURCE 大都为 Mark Annotation,这类 Annotation 大都用来校验,比如 Override, SuppressWarnings
  • @Target 可以用来修饰哪些程序元素,如 TYPE, METHOD, CONSTRUCTOR, FIELD, PARAMETER 等,未标注则表示可修饰所有 ANONOTATION_TYPE(注解类型声明), PACKAGE(包) TYPE (类,包括enum及接口,注解类型) METHOD (方法) CONSTRUCTOR (构造方法) FIFLD (成员变量) PARAMATER (参数) LOCAL_VARIABLE (局部 变量)
  • @Inherited 是否可以被继承,默认为 false

4)什么是metadata(元数据):

元数据从metadata一词译来,就是“关于数据的数据”的意思。

 元数据的功能作用有很多,比如:你可能用过Javadoc的注释自动生成文档。这就是元数据功能的一种。总的来说,元数据可以用来创建文档,跟踪代码的依赖性,执行编译时格式检查,代替已有的配置文件。如果要对于元数据的作用进行分类,目前还没有明确的定义,不过我们可以根据它所起的作用,大致可分为三类:

  1. 编写文档:通过代码里标识的元数据生成文档
  2. 代码分析:通过代码里标识的元数据对代码进行分析
  3. 编译检查:通过代码里标识的元数据让编译器能实现基本的编译检查

其他知识点暂时不介绍,个人觉得一下子介绍太多概念很难消化。下面让我们一起结合例子来使用它。


下面我们来看一下我们要怎样写一个基于编译时的自定义注解的例子

自定义注解大概可分为以下三个步骤:

  1. 自定义一个注解
  2. 在其他类使用我们的注解
  3. 在运行的时候解析我们的注解

解析运行流程图

1)首先我们我们来看一下我们是怎样自定义一个注解的

这些类型和它们所支持的类在java.lang.annotation包中可以找到。

代码语言:javascript
复制
/* 
 * 定义注解 MethodInfo 
 * 为方便测试:注解目标为类 方法,属性及构造方法 
 * 注解中含有三个元素 id ,name和 gid; 
 * id 元素 有默认值 0
 */ 

@Documented 
@Target({ElementType.TYPE,ElementType.METHOD,
    ElementType.FIELD,ElementType.CONSTRUCTOR})
// 表示在运行时解析
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MethodInfo {
    String name() default "xujunTest";
    int id() default 0;
    Class<Long> gid();
}
解析说明
  • (1). 通过 @interface 定义,注解名即为自定义注解名,这里注解名为MethodInfo
  • (2). 注解配置参数名为注解类的方法名,且: a. 所有方法没有方法体,没有参数没有修饰符,实际只允许 public & abstract 修饰符,默认为 public,不允许抛异常 b. 方法返回值只能是基本类型,String, Class, annotation, enumeration 或者是他们的一维数组 c. 若只有一个默认属性,可直接用 value() 函数。一个属性都没有表示该 Annotation 为 Mark Annotation
  • (3). 可以加 default 表示默认值,如
代码语言:javascript
复制
String name() default "xujunTest";

2)接着我们来看一下我们要怎样使用我们自定义的注解

代码语言:javascript
复制
/**
 * 这个类专门用来测试注解使用
 * @author xujun
 */

@MethodInfo(name="type",gid=Long.class) //类成员注解
public class UserAnnotation {

    @MethodInfo(name="param",id=1,gid=Long.class) //类成员注解
    private Integer age;

    @MethodInfo (name="construct",id=2,gid=Long.class)//构造方法注解
    public UserAnnotation(){

    }
    @MethodInfo(name="public method",id=3,gid=Long.class) //类方法注解
    public void a(){
        Map<String,String> m = new HashMap<String,String>(0);
    }

    @MethodInfo(name="protected method",id=4,gid=Long.class) //类方法注解
    protected void b(){
        Map<String,String> m = new HashMap<String,String>(0);
    }

    @MethodInfo(name="private method",id=5,gid=Long.class) //类方法注解
    private void c(){
        Map<String,String> m = new HashMap<String,String>(0);
    }

    public void b(Integer a){ 

    }
}

3)最后我们一起来看一下我们怎样在运行的时候解析我们的Annotation注解

运行时 Annotation 解析

(1) 运行时 Annotation 指 @Retention 为 RUNTIME 的 Annotation,可手动调用下面常用 API 解析

代码语言:javascript
复制
method.getAnnotation(AnnotationName.class);
method.getAnnotations();
method.isAnnotationPresent(AnnotationName.class);

其他 @Target 如 Field,Class 方法类似

  • getAnnotation(AnnotationName.class) 表示得到该 Target 某个 Annotation 的信息,因为一个 Target 可以被多个 Annotation 修饰
代码语言:javascript
复制
/*
* 根据注解类型返回方法的指定类型注解
*/
MethodInfo annotation = (MethodInfo) constructor
                     .getAnnotation(MethodInfo.class);
  • getAnnotations() 则表示得到该 Target 所有 Annotation
代码语言:javascript
复制
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
    MethodInfo methodInfo = (MethodInfo) annotation
}
  • isAnnotationPresent(AnnotationName.class) 表示该 Target 是否被某个 Annotation 修饰
代码语言:javascript
复制
/*
* 判断构造方法中是否有指定注解类型的注解
*/
boolean hasAnnotation = constructor
.isAnnotationPresent(MethodInfo.class);
if (hasAnnotation) {
    /*
    * 根据注解类型返回方法的指定类型注解
    */
    MethodInfo annotation = (MethodInfo) constructor
    .getAnnotation(MethodInfo.class);
}

测试代码

代码语言:javascript
复制
public class ParseAnnotation {

    static String className="com.xujun.animation.test.UserAnnotation";
    /**
     * 简单打印出UserAnnotation 类中所使用到的类注解 该方法只打印了 Type 类型的注解
     * 
     * @throws ClassNotFoundException
     */
    public static void parseTypeAnnotation() throws ClassNotFoundException {
        Class clazz = Class.forName(className);

        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            MethodInfo testA = (MethodInfo) annotation;
            System.out.println("id= \"" + testA.id() + "\"; name= \""
                    + testA.name() + "\"; gid = " + testA.gid());
        }
    }

    /**
     * 简单打印出UserAnnotation 类中所使用到的方法注解 该方法只打印了 Method 类型的注解
     * 
     * @throws ClassNotFoundException
     */
    public static void parseMethodAnnotation() {
        Method[] methods = UserAnnotation.class.getDeclaredMethods();
        for (Method method : methods) {
            /*
             * 判断方法中是否有指定注解类型的注解
             */
            boolean hasAnnotation = method.isAnnotationPresent(MethodInfo.class);
            if (hasAnnotation) {
                /*
                 * 根据注解类型返回方法的指定类型注解
                 */
                MethodInfo annotation = method.getAnnotation(MethodInfo.class);
                System.out.println("method = " + method.getName() + " ; id = "
                        + annotation.id() + " ; description = "
                        + annotation.name() + "; gid= " + annotation.gid());
            }
        }
    }

    /**
     * 简单打印出UserAnnotation 类中所使用到的方法注解 该方法只打印了 Method 类型的注解
     * 
     * @throws ClassNotFoundException
     */
    public static void parseConstructAnnotation() {
        Constructor[] constructors = UserAnnotation.class.getConstructors();
        for (Constructor constructor : constructors) {
            /*
             * 判断构造方法中是否有指定注解类型的注解
             */
            boolean hasAnnotation = constructor
                    .isAnnotationPresent(MethodInfo.class);
            if (hasAnnotation) {
                /*
                 * 根据注解类型返回方法的指定类型注解
                 */
                MethodInfo annotation = (MethodInfo) constructor
                        .getAnnotation(MethodInfo.class);
                System.out.println("constructor = " + constructor.getName()
                        + " ; id = " + annotation.id() + " ; description = "
                        + annotation.name() + "; gid= " + annotation.gid());
            }
        }
    }

    public static void main(String[] args) throws ClassNotFoundException {
        parseTypeAnnotation();
        parseMethodAnnotation();
        parseConstructAnnotation();
    }
}

运行以上测试程序,将可以看到以下输出结果

id= “0”; name= “type”; gid = class java.lang.Long method = c ; id = 5 ; description = private method; gid= class java.lang.Long method = b ; id = 4 ; description = protected method; gid= class java.lang.Long method = a ; id = 3 ; description = public method; gid= class java.lang.Long constructor = com.xujun.animationdemo.UserAnnotation ; id = 2 ; description = construct; gid= class java.lang.Long


转载请注明原博客地址:

源码下载地址:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016年07月24日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 本篇博客要讲解主要分为以下几个问题
  • 注解的相关知识点
    • 1)什么是注解(Annotation):
      • 2)注解的分类:
        • 3)元注解:
          • 4)什么是metadata(元数据):
          • 下面我们来看一下我们要怎样写一个基于编译时的自定义注解的例子
            • 解析运行流程图
              • 1)首先我们我们来看一下我们是怎样自定义一个注解的
                • 解析说明
              • 2)接着我们来看一下我们要怎样使用我们自定义的注解
                • 3)最后我们一起来看一下我们怎样在运行的时候解析我们的Annotation注解
                  • 运行时 Annotation 解析
                • 测试代码
                相关产品与服务
                腾讯云代码分析
                腾讯云代码分析(内部代号CodeDog)是集众多代码分析工具的云原生、分布式、高性能的代码综合分析跟踪管理平台,其主要功能是持续跟踪分析代码,观测项目代码质量,支撑团队传承代码文化。
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档