java 注解是在 JDK5 时引入的新特性,鉴于目前大部分框架(如Spring)都使用了注解简化代码并提高编码的效率,因此掌握并深入理解注解对于一个Java工程师是来说是很有必要的事。

理解Java注解

实际上 Java 注解与普通修饰符 (public、static、void 等) 的使用方式并没有多大区别,下面的例子是常见的注解:

  1. public class AnnotationDemo {
  2. //@Test注解修饰方法A
  3. @Test
  4. public static void A(){
  5. System.out.println("Test.....");
  6. }
  7. //一个方法上可以拥有多个不同的注解
  8. @Deprecated
  9. @SuppressWarnings("uncheck")
  10. public static void B(){
  11. }
  12. }

通过在方法上使用 @Test 注解后,在运行该方法时,测试框架会自动识别该方法并单独调用,@Test 实际上是一种标记注解,起标记作用,运行时告诉测试框架该方法为测试方法。而对于 @Deprecated@SuppressWarnings(“uncheck”),则是 Java 本身内置的注解,在代码中,可以经常看见它们,但这并不是一件好事,毕竟当方法或是类上面有 @Deprecated 注解时,说明该方法或是类都已经过期不建议再用,@SuppressWarnings 则表示忽略指定警告,比如 @SuppressWarnings(“uncheck”),这就是注解的最简单的使用方式,那么下面我们就来看看注解定义的基本语法

基本语法

声明注解与元注解

我们先来看看前面的 @Test 注解是如何声明的:

  1. //声明Test注解
  2. @Target(ElementType.METHOD)
  3. @Retention(RetentionPolicy.RUNTIME)
  4. public @interface Test {
  5. }
  1. 使用了@interface声明了 Test 注解,
  2. 使用@Target注解传入ElementType.METHOD参数来标明 @Test 只能用于方法上
  3. 使用@Retention(RetentionPolicy.RUNTIME)表示该注解生存期是运行时

从代码上看注解的定义很像接口的定义,确实如此,毕竟在编译后也会生成 Test.class文件
对于@Target@Retention是由Java提供的元注解,所谓元注解就是标记其他注解的注解,下面分别介绍:

  • @Target 用来约束注解可以应用的地方(如方法、类或字段),其中 ElementType 是枚举类型,其定义如下,也代表可能的取值范围

    • 请注意,当注解未指定 Target 值时,则此注解可以用于任何元素之上,多个值使用 {} 包含并用逗号隔开,如下:
    • @Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})

      1. public enum ElementType {
      2. /**标明该注解可以用于类、接口(包括注解类型)或enum声明*/
      3. TYPE,
      4. /** 标明该注解可以用于字段(域)声明,包括 enum 实例 */
      5. FIELD,
      6. /** 标明该注解可以用于方法声明 */
      7. METHOD,
      8. /** 标明该注解可以用于参数声明 */
      9. PARAMETER,
      10. /** 标明注解可以用于构造函数声明 */
      11. CONSTRUCTOR,
      12. /** 标明注解可以用于局部变量声明 */
      13. LOCAL_VARIABLE,
      14. /** 标明注解可以用于注解声明(应用于另一个注解上)*/
      15. ANNOTATION_TYPE,
      16. /** 标明注解可以用于包声明 */
      17. PACKAGE,
      18. /**
      19. * 标明注解可以用于类型参数声明(1.8新加入)
      20. * @since 1.8
      21. */
      22. TYPE_PARAMETER,
      23. /**
      24. * 类型使用声明(1.8新加入)
      25. * @since 1.8
      26. */
      27. TYPE_USE
      28. }
  • @Retention 用来约束注解的生命周期,分别有三个值,源码级别(source),类文件级别(class)或者运行时级别(runtime)

    • SOURCE:注解将被编译器丢弃(该类型的注解信息只会保留在源码里,源码经过编译后,注解信息会被丢弃,不会保留在编译好的 class 文件里
    • CLASS:注解在 class 文件中可用,但会被 VM 丢弃(该类型的注解信息会保留在源码里和 class 文件里,在执行的时候,不会加载到虚拟机中,一般就用于编译过程的检查),请注意,当注解未定义Retention值时,默认值是 CLASS,如 Java 内置注解,@Override、@Deprecated、@SuppressWarnning 等
    • RUNTIME:注解信息将在运行期(JVM)也保留,因此可以通过反射机制读取注解的信息(详见后文)(源码、class文件和执行的时候都有注解的信息),如 SpringMvc 中的 @Controller、@Autowired、@RequestMapping 等。

      注解元素及其数据类型

      通过上述对 @Test 注解的定义,我们了解了注解定义的过程,由于 @Test 内部没有定义其他元素,所以 @Test 也称为标记注解(marker annotation),但在自定义注解中,一般都会包含一些元素以表示某些值,方便处理器使用,这点在下面的例子将会看到:
      1. /**
      2. * Created by wuzejian on 2017/5/18.
      3. * 对应数据表注解
      4. */
      5. @Target(ElementType.TYPE)//只能应用于类上
      6. @Retention(RetentionPolicy.RUNTIME)//保存到运行时
      7. public @interface DBTable {
      8. String name() default "";
      9. }
      上述定义一个名为 DBTable 的注解,该用于主要用于数据库表与 Bean 类的映射(稍后会有完整案例分析),与前面 Test 注解不同的是,我们声明一个String 类型的 name 元素,其默认值为空字符,但是必须注意到对应任何元素的声明应采用方法的声明方式,同时可选择使用 default 提供默认值
      @DBTable 使用方式如下:
      1. //在类上使用该注解
      2. @DBTable(name = "MEMBER")
      3. public class Member {
      4. //.......
      5. }
      关于注解支持的元素数据类型除了上述的String,还支持如下数据类型
  • 所有基本类型(int,float,boolean,byte,double,char,long,short)

  • String
  • Class
  • enum
  • Annotation
  • 上述类型的数组

倘若使用了其他数据类型,编译器将会丢出一个编译错误,注意,声明注解元素时可以使用基本类型但不允许使用任何包装类型,同时还应该注意到注解也可以作为元素的类型,也就是嵌套注解,下面的代码演示了上述类型的使用过程:

  1. package com.zejian.annotationdemo;
  2. import java.lang.annotation.ElementType;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. /**
  7. * Created by wuzejian on 2017/5/19.
  8. * 数据类型使用Demo
  9. */
  10. @Target(ElementType.TYPE)
  11. @Retention(RetentionPolicy.RUNTIME)
  12. @interface Reference{
  13. boolean next() default false;
  14. }
  15. public @interface AnnotationElementDemo {
  16. //枚举类型
  17. enum Status {FIXED,NORMAL};
  18. //声明枚举
  19. Status status() default Status.FIXED;
  20. //布尔类型
  21. boolean showSupport() default false;
  22. //String类型
  23. String name()default "";
  24. //class类型
  25. Class<?> testCase() default Void.class;
  26. //注解嵌套
  27. Reference reference() default @Reference(next=true);
  28. //数组类型
  29. long[] value();
  30. }

编译器对默认值的限制

编译器对元素的默认值有些过分挑剔。

  1. 元素不能有不确定的值。也就是说,元素必须要么具有默认值,要么在使用注解时提供元素的值。
  2. 对于非基本类型的元素,无论是在源代码中声明,还是在注解接口中定义默认值,都不能以 **null** 作为值,这就是限制,没有什么利用可言,但造成一个元素的存在或缺失状态,因为每个注解的声明中,所有的元素都存在,并且都具有相应的值,为了绕开这个限制,只能定义一些特殊的值,例如空字符串或负数,表示某个元素不存在。

    注解不支持继承

    注解是不支持继承的,因此不能使用关键字 extends 来继承某个 @interface,但注解在编译后,编译器会自动继承 java.lang.annotation.Annotation 接口,这里我们反编译前面定义的DBTable注解 ```java package com.zejian.annotationdemo;

import java.lang.annotation.Annotation; //反编译后的代码 public interface DBTable extends Annotation { public abstract String name(); }

  1. 虽然反编译后发现 DBTable 注解继承了 Annotation 接口,请记住,即使 Java 的接口可以实现多继承,但定义注解时依然无法使用 extends 关键字继承@interface
  2. <a name="457daa95"></a>
  3. ## 快捷方式
  4. 所谓的快捷方式就是注解中定义了名为 value 的元素,并且在使用该注解时,如果该元素是唯一需要赋值的一个元素,那么此时无需使用 `key=value` 的语法,而只需在括号内给出 value 元素所需的值即可。这可以应用于任何合法类型的元素,记住,这**限制了元素名必须为 value**,简单案例如下
  5. ```java
  6. package com.zejian.annotationdemo;
  7. import java.lang.annotation.ElementType;
  8. import java.lang.annotation.Retention;
  9. import java.lang.annotation.RetentionPolicy;
  10. import java.lang.annotation.Target;
  11. /**
  12. * Created by zejian on 2017/5/20.
  13. * Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创]
  14. */
  15. //定义注解
  16. @Target(ElementType.FIELD)
  17. @Retention(RetentionPolicy.RUNTIME)
  18. @interface IntegerVaule{
  19. int value() default 0;
  20. String name() default "";
  21. }
  22. //使用注解
  23. public class QuicklyWay {
  24. //当只想给value赋值时,可以使用以下快捷方式
  25. @IntegerVaule(20)
  26. public int age;
  27. //当name也需要赋值时必须采用key=value的方式赋值
  28. @IntegerVaule(value = 10000,name = "MONEY")
  29. public int money;
  30. }

Java内置注解与其它元注解

接着看看Java提供的内置注解,主要有3个,如下:

  • @Override:用于标明此方法覆盖了父类的方法,源码如下

    1. @Target(ElementType.METHOD)
    2. @Retention(RetentionPolicy.SOURCE)
    3. public @interface Override {
    4. }
  • @Deprecated:用于标明已经过时的方法或类,源码如下,关于@Documented稍后分析:

    1. @Documented
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
    4. public @interface Deprecated {
    5. }
  • @SuppressWarnnings:用于有选择的关闭编译器对类、方法、成员变量、变量初始化的警告,其实现源码如下

    1. @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
    2. @Retention(RetentionPolicy.SOURCE)
    3. public @interface SuppressWarnings {
    4. String[] value();
    5. }

    其内部有一个String数组,主要接收值如下:

    1. deprecation:使用了不赞成使用的类或方法时的警告;
    2. unchecked:执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型;
    3. fallthrough:当 Switch 程序块直接通往下一种情况而没有 Break 时的警告;
    4. path:在类路径、源文件路径等中有不存在的路径时的警告;
    5. serial:当在可序列化的类上缺少 serialVersionUID 定义时的警告;
    6. finally:任何 finally 子句不能正常完成时的警告;
    7. all:关于以上所有情况的警告。

    这个三个注解比较简单,看个简单案例即可: ```java //注明该类已过时,不建议使用 @Deprecated class A{ public void A(){ }

    //注明该方法已过时,不建议使用 @Deprecated() public void B(){ } }

class B extends A{

  1. @Override //标明覆盖父类A的A方法
  2. public void A() {
  3. super.A();
  4. }
  5. //去掉检测警告
  6. @SuppressWarnings({"uncheck","deprecation"})
  7. public void C(){ }
  8. //去掉检测警告
  9. @SuppressWarnings("uncheck")
  10. public void D(){ }

}

  1. 前面我们分析了两种元注解,`@Target` `@Retention`,除了这两种元注解,Java还提供了另外两种元注解,`@Documented` `@Inherited`,下面分别介绍:
  2. - `@Documented` 被修饰的注解会生成到javadoc
  3. ```java
  4. /**
  5. * Created by zejian on 2017/5/20.
  6. * Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创]
  7. */
  8. @Documented
  9. @Target(ElementType.TYPE)
  10. @Retention(RetentionPolicy.RUNTIME)
  11. public @interface DocumentA {
  12. }
  13. //没有使用@Documented
  14. @Target(ElementType.TYPE)
  15. @Retention(RetentionPolicy.RUNTIME)
  16. public @interface DocumentB {
  17. }
  18. //使用注解
  19. @DocumentA
  20. @DocumentB
  21. public class DocumentDemo {
  22. public void A(){
  23. }
  24. }
  • 使用javadoc命令生成文档:$ javadoc DocumentDemo.java DocumentA.java DocumentB.java
    如下:
    理解Java注解类型(@Annotation) - 图1
    可以发现使用 @Documented 元注解定义的注解(@DocumentA)将会生成到 javadoc 中,而 @DocumentB 则没有在 doc 文档中出现,这就是元注解@Documented 的作用。
    • @Inherited 可以让注解被继承,但这并不是真的继承,只是通过使用@Inherited,可以让子类Class对象使用 getAnnotations() 获取父类被@Inherited修饰的注解,如下:
      ```java @Inherited @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DocumentA { }

@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DocumentB { }

@DocumentA class A{ }

class B extends A{ }

@DocumentB class C{ }

class D extends C{ }

//测试 public class DocumentDemo {

  1. public static void main(String... args){
  2. A instanceA=new B();
  3. System.out.println("已使用的@Inherited注解:"+Arrays.toString(instanceA.getClass().getAnnotations()));
  4. C instanceC = new D();
  5. System.out.println("没有使用的@Inherited注解:"+Arrays.toString(instanceC.getClass().getAnnotations()));
  6. }
  7. /**
  8. * 运行结果:
  9. 已使用的@Inherited注解:[@com.zejian.annotationdemo.DocumentA()]
  10. 没有使用的@Inherited注解:[]
  11. */

}

  1. <a name="59b4cabc"></a>
  2. # 注解与反射机制
  3. 前面经过反编译后,我们知道** Java 所有注解都继承了 Annotation 接口**,也就是说 **Java 使用 Annotation 接口代表注解元素**,该接口是所有Annotation 类型的父接口。同时为了运行时能准确获取到注解的相关信息,Java在 `java.lang.reflect` 反射包下新增了 AnnotatedElement 接口,它主要用于表示目前正在 VM 中运行的程序中已使用注解的元素,通过该接口提供的方法可以利用反射技术地读取注解的信息,如反射包的 Constructor类、Field 类、Method 类、Package 类和 Class 类**都实现了 AnnotatedElement 接口**,它简要含义如下(更多详细介绍可以看 [深入理解Java类型信息(Class对象)与反射机制](http://blog.csdn.net/javazejian/article/details/70768369)):<br />注意:**注解生命周期必须为**`**@Retention(RetentionPolicy.RUNTIME)**`,**即运行时,这样才可以使用反射机制获取其信息**
  4. > Class:类的Class对象定义   <br />Constructor:代表类的构造器定义   <br />Field:代表类的成员变量定义 <br />Method:代表类的方法定义   <br />Package:代表类的包定义
  5. 下面是 AnnotatedElement 中相关的API方法,以上5个类都实现以下的方法
  6. | 返回值 | 方法名称 | 说明 |
  7. | --- | --- | --- |
  8. | `<A extends Annotation>` | `getAnnotation(Class<A> annotationClass)` | 该元素如果存在指定类型的注解,则返回这些注解,否则返回 null。 |
  9. | `Annotation[]` | `getAnnotations()` | 返回此元素上存在的所有注解,包括从父类继承的 |
  10. | `boolean` | `isAnnotationPresent(Class<? extends Annotation> annotationClass)` | 如果指定类型的注解存在于此元素上,则返回 true,否则返回 false。 |
  11. | `Annotation[]` | `getDeclaredAnnotations()` | 返回直接存在于此元素上的所有注解,注意,不包括父类的注解,调用者可以随意修改返回的数组;这不会对其他调用者返回的数组产生任何影响,没有则返回长度为0的数组 |
  12. 简单案例演示如下:
  13. ```java
  14. package com.zejian.annotationdemo;
  15. import java.lang.annotation.Annotation;
  16. import java.util.Arrays;
  17. @DocumentA
  18. class A{ }
  19. //继承了A类
  20. @DocumentB
  21. public class DocumentDemo extends A{
  22. public static void main(String... args){
  23. Class<?> clazz = DocumentDemo.class;
  24. //根据指定注解类型获取该注解
  25. DocumentA documentA=clazz.getAnnotation(DocumentA.class);
  26. System.out.println("A:"+documentA);
  27. //获取该元素上的所有注解,包含从父类继承
  28. Annotation[] an= clazz.getAnnotations();
  29. System.out.println("an:"+ Arrays.toString(an));
  30. //获取该元素上的所有注解,但不包含继承!
  31. Annotation[] an2=clazz.getDeclaredAnnotations();
  32. System.out.println("an2:"+ Arrays.toString(an2));
  33. //判断注解DocumentA是否在该元素上
  34. boolean b=clazz.isAnnotationPresent(DocumentA.class);
  35. System.out.println("b:"+b);
  36. /**
  37. * 执行结果:
  38. A:@com.zejian.annotationdemo.DocumentA()
  39. an:[@com.zejian.annotationdemo.DocumentA(), @com.zejian.annotationdemo.DocumentB()]
  40. an2:@com.zejian.annotationdemo.DocumentB()
  41. b:true
  42. */
  43. }
  44. }

运行时注解处理器

了解完注解与反射的相关 API 后,现在通过一个实例(该例子是博主改编自《Tinking in Java》)来演示利用运行时注解来组装数据库 SQL 的构建语句的过程

  1. /**
  2. * 表注解
  3. */
  4. @Target(ElementType.TYPE)//只能应用于类上
  5. @Retention(RetentionPolicy.RUNTIME)//保存到运行时
  6. public @interface DBTable {
  7. String name() default "";
  8. }
  9. /**
  10. * 注解Integer类型的字段
  11. */
  12. @Target(ElementType.FIELD)
  13. @Retention(RetentionPolicy.RUNTIME)
  14. public @interface SQLInteger {
  15. //该字段对应数据库表列名
  16. String name() default "";
  17. //嵌套注解
  18. Constraints constraint() default @Constraints;
  19. }
  20. /**
  21. * 注解String类型的字段
  22. */
  23. @Target(ElementType.FIELD)
  24. @Retention(RetentionPolicy.RUNTIME)
  25. public @interface SQLString {
  26. //对应数据库表的列名
  27. String name() default "";
  28. //列类型分配的长度,如varchar(30)的30
  29. int value() default 0;
  30. Constraints constraint() default @Constraints;
  31. }
  32. /**
  33. * 约束注解
  34. */
  35. @Target(ElementType.FIELD)//只能应用在字段上
  36. @Retention(RetentionPolicy.RUNTIME)
  37. public @interface Constraints {
  38. //判断是否作为主键约束
  39. boolean primaryKey() default false;
  40. //判断是否允许为null
  41. boolean allowNull() default false;
  42. //判断是否唯一
  43. boolean unique() default false;
  44. }
  45. /**
  46. * 数据库表Member对应实例类bean
  47. */
  48. @DBTable(name = "MEMBER")
  49. public class Member {
  50. //主键ID
  51. @SQLString(name = "ID",value = 50, constraint = @Constraints(primaryKey = true))
  52. private String id;
  53. @SQLString(name = "NAME" , value = 30)
  54. private String name;
  55. @SQLInteger(name = "AGE")
  56. private int age;
  57. @SQLString(name = "DESCRIPTION" ,value = 150 , constraint = @Constraints(allowNull = true))
  58. private String description;//个人描述
  59. //省略set get.....
  60. }

上述定义4个注解,分别是 @DBTable(用于类上)、@Constraints(用于字段上)、 @SQLString(用于字段上)、@SQLString(用于字段上)并在 Member 类中使用这些注解,这些注解的作用的是用于帮助注解处理器生成创建数据库表 MEMBER 的构建语句,在这里有点需要注意的是,我们使用了嵌套注解 @Constraints,该注解主要用于判断字段是否为 null 或者字段是否唯一。必须清楚认识到上述提供的注解生命周期必须为**@Retention(RetentionPolicy.RUNTIME)**即运行时,这样才可以使用反射机制获取其信息。有了上述注解和使用,剩余的就是编写上述的注解处理器了,前面我们聊了很多注解,其处理器要么是Java自身已提供、要么是框架已提供的,我们自己都没有涉及到注解处理器的编写,但上述定义处理SQL的注解,其处理器必须由我们自己编写了,如下

  1. package com.zejian.annotationdemo;
  2. import java.lang.annotation.Annotation;
  3. import java.lang.reflect.Field;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. /**
  7. * Created by zejian on 2017/5/13.
  8. * Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创]
  9. * 运行时注解处理器,构造表创建语句
  10. */
  11. public class TableCreator {
  12. public static String createTableSql(String className) throws ClassNotFoundException {
  13. Class<?> cl = Class.forName(className);
  14. DBTable dbTable = cl.getAnnotation(DBTable.class);
  15. //如果没有表注解,直接返回
  16. if(dbTable == null) {
  17. System.out.println(
  18. "No DBTable annotations in class " + className);
  19. return null;
  20. }
  21. String tableName = dbTable.name();
  22. // If the name is empty, use the Class name:
  23. if(tableName.length() < 1)
  24. tableName = cl.getName().toUpperCase();
  25. List<String> columnDefs = new ArrayList<String>();
  26. //通过Class类API获取到所有成员字段
  27. for(Field field : cl.getDeclaredFields()) {
  28. String columnName = null;
  29. //获取字段上的注解
  30. Annotation[] anns = field.getDeclaredAnnotations();
  31. if(anns.length < 1)
  32. continue; // Not a db table column
  33. //判断注解类型
  34. if(anns[0] instanceof SQLInteger) {
  35. SQLInteger sInt = (SQLInteger) anns[0];
  36. //获取字段对应列名称,如果没有就是使用字段名称替代
  37. if(sInt.name().length() < 1)
  38. columnName = field.getName().toUpperCase();
  39. else
  40. columnName = sInt.name();
  41. //构建语句
  42. columnDefs.add(columnName + " INT" +
  43. getConstraints(sInt.constraint()));
  44. }
  45. //判断String类型
  46. if(anns[0] instanceof SQLString) {
  47. SQLString sString = (SQLString) anns[0];
  48. // Use field name if name not specified.
  49. if(sString.name().length() < 1)
  50. columnName = field.getName().toUpperCase();
  51. else
  52. columnName = sString.name();
  53. columnDefs.add(columnName + " VARCHAR(" +
  54. sString.value() + ")" +
  55. getConstraints(sString.constraint()));
  56. }
  57. }
  58. //数据库表构建语句
  59. StringBuilder createCommand = new StringBuilder(
  60. "CREATE TABLE " + tableName + "(");
  61. for(String columnDef : columnDefs)
  62. createCommand.append("\n " + columnDef + ",");
  63. // Remove trailing comma
  64. String tableCreate = createCommand.substring(
  65. 0, createCommand.length() - 1) + ");";
  66. return tableCreate;
  67. }
  68. /**
  69. * 判断该字段是否有其他约束
  70. * @param con
  71. * @return
  72. */
  73. private static String getConstraints(Constraints con) {
  74. String constraints = "";
  75. if(!con.allowNull())
  76. constraints += " NOT NULL";
  77. if(con.primaryKey())
  78. constraints += " PRIMARY KEY";
  79. if(con.unique())
  80. constraints += " UNIQUE";
  81. return constraints;
  82. }
  83. public static void main(String[] args) throws Exception {
  84. String[] arg={"com.zejian.annotationdemo.Member"};
  85. for(String className : arg) {
  86. System.out.println("Table Creation SQL for " +
  87. className + " is :\n" + createTableSql(className));
  88. }
  89. /**
  90. * 输出结果:
  91. Table Creation SQL for com.zejian.annotationdemo.Member is :
  92. CREATE TABLE MEMBER(
  93. ID VARCHAR(50) NOT NULL PRIMARY KEY,
  94. NAME VARCHAR(30) NOT NULL,
  95. AGE INT NOT NULL,
  96. DESCRIPTION VARCHAR(150)
  97. );
  98. */
  99. }
  100. }

如果对反射比较熟悉的同学,上述代码就相对简单了,我们通过传递 Member 的全路径后通过 Class.forName() 方法获取到 Member 的 class 对象,然后利用 Class 对象中的方法获取所有成员字段 Field,最后利用field.getDeclaredAnnotations()遍历每个 Field 上的注解再通过注解的类型判断来构建建表的 SQL 语句。这便是利用注解结合反射来构建SQL语句的简单的处理器模型,是否已回想起 Hibernate?

Java 8中注解增强

元注解@Repeatable

元注解@Repeatable是JDK1.8新加入的,它表示在同一个位置重复相同的注解。在没有该注解前,一般是无法在同一个类型上使用相同的注解的

  1. //Java8前无法这样使用
  2. @FilterPath("/web/update")
  3. @FilterPath("/web/add")
  4. public class A {}

Java8前如果是想实现类似的功能,我们需要在定义@FilterPath注解时定义一个数组元素接收多个值如下

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. public @interface FilterPath {
  4. String [] value();
  5. }
  6. //使用
  7. @FilterPath({"/update","/add"})
  8. public class A { }

但在Java8新增了 @Repeatable 注解后就可以采用如下的方式定义并使用了

  1. package com.zejian.annotationdemo;
  2. import java.lang.annotation.*;
  3. //使用Java8新增@Repeatable原注解
  4. @Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
  5. @Retention(RetentionPolicy.RUNTIME)
  6. @Repeatable(FilterPaths.class)//参数指明接收的注解class
  7. public @interface FilterPath {
  8. String value();
  9. }
  10. @Target(ElementType.TYPE)
  11. @Retention(RetentionPolicy.RUNTIME)
  12. @interface FilterPaths {
  13. FilterPath[] value();
  14. }
  15. //使用案例
  16. @FilterPath("/web/update")
  17. @FilterPath("/web/add")
  18. @FilterPath("/web/delete")
  19. class AA{ }

我们可以简单理解为通过使用 @Repeatable 后,将使用 @FilterPaths 注解作为接收同一个类型上重复注解的容器,而每个 @FilterPath 则负责保存指定的路径串。为了处理上述的新增注解,Java8 还在 AnnotatedElement 接口新增了 getDeclaredAnnotationsByType()getAnnotationsByType() 两个方法并在接口给出了默认实现,在指定 @Repeatable 的注解时,可以通过这两个方法获取到注解相关信息。但请注意,旧版 API 中的 getDeclaredAnnotation()getAnnotation() 是不对 @Repeatable 注解的处理的(除非该注解没有在同一个声明上重复出现)。注意 getDeclaredAnnotationsByType()方法获取到的注解不包括父类,其实当 getAnnotationsByType() 方法调用时,其内部先执行了 getDeclaredAnnotationsByType() 方法,只有当前类不存在指定注解时,getAnnotationsByType() 才会继续从其父类寻找,但请注意如果 @FilterPath@FilterPaths 没有使用 @Inherited 的话,仍然无法获取。下面通过代码来演示:

  1. /**
  2. * Created by zejian on 2017/5/20.
  3. * Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创]
  4. */
  5. //使用Java8新增@Repeatable原注解
  6. @Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
  7. @Retention(RetentionPolicy.RUNTIME)
  8. @Repeatable(FilterPaths.class)
  9. public @interface FilterPath {
  10. String value();
  11. }
  12. @Target(ElementType.TYPE)
  13. @Retention(RetentionPolicy.RUNTIME)
  14. @interface FilterPaths {
  15. FilterPath[] value();
  16. }
  17. @FilterPath("/web/list")
  18. class CC { }
  19. //使用案例
  20. @FilterPath("/web/update")
  21. @FilterPath("/web/add")
  22. @FilterPath("/web/delete")
  23. class AA extends CC{
  24. public static void main(String[] args) {
  25. Class<?> clazz = AA.class;
  26. //通过getAnnotationsByType方法获取所有重复注解
  27. FilterPath[] annotationsByType = clazz.getAnnotationsByType(FilterPath.class);
  28. FilterPath[] annotationsByType2 = clazz.getDeclaredAnnotationsByType(FilterPath.class);
  29. if (annotationsByType != null) {
  30. for (FilterPath filter : annotationsByType) {
  31. System.out.println("1:"+filter.value());
  32. }
  33. }
  34. System.out.println("-----------------");
  35. if (annotationsByType2 != null) {
  36. for (FilterPath filter : annotationsByType2) {
  37. System.out.println("2:"+filter.value());
  38. }
  39. }
  40. System.out.println("使用getAnnotation的结果:"+clazz.getAnnotation(FilterPath.class));
  41. /**
  42. * 执行结果(当前类拥有该注解FilterPath,则不会从CC父类寻找)
  43. 1:/web/update
  44. 1:/web/add
  45. 1:/web/delete
  46. -----------------
  47. 2:/web/update
  48. 2:/web/add
  49. 2:/web/delete
  50. 使用getAnnotation的结果:null
  51. */
  52. }
  53. }

从执行结果来看如果当前类拥有该注解 @FilterPath,则 getAnnotationsByType 方法不会从CC父类寻找,下面看看另外一种情况,即AA类上没有 @FilterPath 注解

  1. /**
  2. * Created by zejian on 2017/5/20.
  3. * Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创]
  4. */
  5. //使用Java8新增@Repeatable原注解
  6. @Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
  7. @Retention(RetentionPolicy.RUNTIME)
  8. @Inherited //添加可继承元注解
  9. @Repeatable(FilterPaths.class)
  10. public @interface FilterPath {
  11. String value();
  12. }
  13. @Target(ElementType.TYPE)
  14. @Retention(RetentionPolicy.RUNTIME)
  15. @Inherited //添加可继承元注解
  16. @interface FilterPaths {
  17. FilterPath[] value();
  18. }
  19. @FilterPath("/web/list")
  20. @FilterPath("/web/getList")
  21. class CC { }
  22. //AA上不使用@FilterPath注解,getAnnotationsByType将会从父类查询
  23. class AA extends CC{
  24. public static void main(String[] args) {
  25. Class<?> clazz = AA.class;
  26. //通过getAnnotationsByType方法获取所有重复注解
  27. FilterPath[] annotationsByType = clazz.getAnnotationsByType(FilterPath.class);
  28. FilterPath[] annotationsByType2 = clazz.getDeclaredAnnotationsByType(FilterPath.class);
  29. if (annotationsByType != null) {
  30. for (FilterPath filter : annotationsByType) {
  31. System.out.println("1:"+filter.value());
  32. }
  33. }
  34. System.out.println("-----------------");
  35. if (annotationsByType2 != null) {
  36. for (FilterPath filter : annotationsByType2) {
  37. System.out.println("2:"+filter.value());
  38. }
  39. }
  40. System.out.println("使用getAnnotation的结果:"+clazz.getAnnotation(FilterPath.class));
  41. /**
  42. * 执行结果(当前类没有@FilterPath,getAnnotationsByType方法从CC父类寻找)
  43. 1:/web/list
  44. 1:/web/getList
  45. -----------------
  46. 使用getAnnotation的结果:null
  47. */
  48. }
  49. }

注意定义 @FilterPath@FilterPaths 时必须指明 @InheritedgetAnnotationsByType方法否则依旧无法从父类获取 @FilterPath注解,这是为什么呢,不妨看看 getAnnotationsByType 方法的实现源码:

  1. //接口默认实现方法
  2. default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
  3. //先调用getDeclaredAnnotationsByType方法
  4. T[] result = getDeclaredAnnotationsByType(annotationClass);
  5. //判断当前类获取到的注解数组是否为0
  6. if (result.length == 0 && this instanceof Class &&
  7. //判断定义注解上是否使用了@Inherited元注解
  8. AnnotationType.getInstance(annotationClass).isInherited()) { // Inheritable
  9. //从父类获取
  10. Class<?> superClass = ((Class<?>) this).getSuperclass();
  11. if (superClass != null) {
  12. result = superClass.getAnnotationsByType(annotationClass);
  13. }
  14. }
  15. return result;
  16. }

新增的两种ElementType

在Java8中 ElementType 新增两个枚举成员,TYPE_PARAMETERTYPE_USE ,在 Java8 前注解只能标注在一个声明(如字段、类、方法)上,Java8后,新增的 TYPE_PARAMETER 可以用于标注类型参数,而 TYPE_USE 则可以用于标注任意类型(不包括class)。如下所示

  1. //TYPE_PARAMETER 标注在类型参数上
  2. class D<@Parameter T> { }
  3. //TYPE_USE则可以用于标注任意类型(不包括class)
  4. //用于父类或者接口
  5. class Image implements @Rectangular Shape { }
  6. //用于构造函数
  7. new @Path String("/usr/bin")
  8. //用于强制转换和instanceof检查,注意这些注解中用于外部工具,它们不会对类型转换或者instanceof的检查行为带来任何影响。
  9. String path=(@Path String)input;
  10. if(input instanceof @Path String)
  11. //用于指定异常
  12. public Person read() throws @Localized IOException.
  13. //用于通配符绑定
  14. List<@ReadOnly ? extends Person>
  15. List<? extends @ReadOnly Person>
  16. @NotNull String.class //非法,不能标注class
  17. import java.lang.@NotNull String //非法,不能标注import

这里主要说明一下 TYPE_USE,类型注解用来支持在 Java 的程序中做强类型检查,配合第三方插件工具(如 Checker Framework),可以在编译期检测出 runtime error(如 UnsupportedOperationException、NullPointerException 异常),避免异常延续到运行期才发现,从而提高代码质量,这就是类型注解的主要作用。总之Java 8 新增加了两个注解的元素类型 ElementType.TYPE_USEElementType.TYPE_PARAMETER ,通过它们,我们可以把注解应用到各种新场合中。