聊聊 java 注解

概述

在上一篇Retrofit 2.0 的使用中可以看到很多应用了注解的地方,例如:

@HTTP(method = "get", path = "userInfo/{userId}", hasBody = false)
Call getCardNum(@Path("userId") int id);

那什么是注解呢?可以看下 Google 得到的解释

JDK 5中引入了源代码中的注解(annotation)这一机制。 注解使得Java源代码中不但可以包含功能性的实现代码,还可以添加元数据。 注解的功能类似于代码中的注释,所不同的是注解不是提供代码功能的说明,而是实现程序功能的重要组成部分。

通俗点说可以理解为注解是一种标签、说明,用来表示被该注解修饰的一方(可以是类、方法、属性等)的一些含义,例如:

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
                return false;
}

@Override 这个应该很多人都见过的,onInterceptTouchEvent 这个方法被@Override 注解了,告诉编译器说这个方法是重写了父类里面的方法,如果一个类A里面的方法使用了这个注解,但是类A 的父类B里面没有这个方法的话编译器就会报错。

元注解

注解一般用来注解类、方法、类的属性等,元注解就是用来应用在注解上的注解,元字代表它是一种根源上的东西,用来修饰说明被应用的注解的含义及应用范围。java 中元注解有这么几个:@Retention、@Documented、@Target、@Inherited,java 7 版本开始增加了 @SafeVarargs、@FunctionalInterface(java 8 开始支持)、@Repeatable(java 8 开始支持)

  • @Retention:标注被@Retention 修饰的注解要怎么保存
  • @Documented:标注被@Documented 修饰的注解是否包含在用户文档中
  • @Target:表明@Target可以注解于哪种 java 成员,被@Target(METHOD) 注解的注解只能用于 method
  • @Inherited 继承,表明被@Inherited 修饰了的注解应用时会传递到子类,如果子类没有被其他注解应用的话。
  • @SafeVarargs 忽略任何使用参数为泛型变量的方法或构造函数调用产生的警告
  • @FunctionalInterface 标识一个匿名函数或函数式接口
  • @Repeatable 表明被@Repeatable修饰了的注解去应用时可以有多个值,比如
@interface Roles {
    Role[]  value();
}

@Repeatable(Roles.class)
@interface Role{
    String value default "";
}

@Person(value="A")
@Person(value="B")
public class Man{

}

一个注解的Hello World

1、定义一个注解

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface HelloAnnotation {
  String msg() default "Hello Wolrd";
}

注解由 @interface 声明,上面的例子中"String msg()" 是声明一个成员变量,并不是一个成员方法,需要注意的是注解只有成员变量,没有成员方法,default 后面代表的是该成员变量的一个默认值,如果使用该注解时没有传参数值使用默认值。

2、使用注解

//传入参数值
@Msg(msg = "Hello TestA")
public class TestA{
    
}
//不传使用默认值
@Msg
public class Test {
    
}

传入参数时使用 “参数名 = 值" 的方式传入,如果定义的注解只有一个成员变量,使用时则可以直接把值传进去,例如:

@Msg( "Hello TestA")
public class TestA{
    
}

注解在 Retrofit 中的使用

回到文章开头使用的例子

@HTTP(method = "get", path = "userInfo/{userId}", hasBody = false)
Call getCardNum(@Path("userId") int id);

看一下@HTTP 的定义

@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface HTTP {
  String method();
  /**
   * A relative or absolute path, or full URL of the endpoint. This value is optional if the first
   * parameter of the method is annotated with {@link Url @Url}.
   * 

* See {@linkplain retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how * this is resolved against a base URL to create the full endpoint URL. */ String path() default ""; boolean hasBody() default false; }

@HTTP 包含三个成员变量,method 声明这个请求的方法是“GET”、“POST”或者是其他,path 和 baseUrl 组成一个完整的请求URL。@HTTP 被 @Target(METHOD) 这个元注解修饰了,说明@HTTP 只能用于修饰方法,@Retention(RUNTIME) 说明了@HTTP 这个注解的生命周期为RetentionPolicy.RUNTIME,所以可以运行时通过反射获取。再来看下getCardNum(@Path("userId") int id) 里面用到的@Path

@Documented
@Retention(RUNTIME)
@Target(PARAMETER)
public @interface Path {
  String value();

  /**
   * Specifies whether the argument value to the annotated method parameter is already URL encoded.
   */
  boolean encoded() default false;
}

@Path 和@HTTP 的不同在于@Path 用于修饰 parameter,同样的是都可以在运行时通过反射获取,在运行时通过反射获取到修饰在getCardNum 这个方法上的注解的值可以得到这是一个 “GET” 请求的方法,path为"userInfo/{userId}",里面有一个userId 需要赋值,再从getCardNum 这个方法中找到被 值为“userId”的@Path 修饰的 parameter,把这个parameter 的值赋予 userId,这样一个 Http 请求就出来了。

以上只是个人学习过程中的理解,可能有错误的地方,希望看到的同学指出错误之处,互相学习。

你可能感兴趣的:(聊聊 java 注解)