简介

插件化注解处理(Pluggable Annotation Processing)APIJSR 269提供一套标准API来处理AnnotationsJSR 175,实际上JSR 269不仅仅用来处理Annotation,我觉得更强大的功能是它建立了Java 语言本身的一个模型,它把method、package、constructor、type、variable、enum、annotation等Java语言元素映射为Types和Elements,从而将Java语言的语义映射成为对象,我们可以在javax.lang.model包下面可以看到这些类。所以我们可以利用JSR 269提供的API来构建一个功能丰富的元编程(metaprogramming)环境。JSR 269用Annotation Processor在编译期间而不是运行期间处理Annotation, Annotation Processor相当于编译器的一个插件,所以称为插入式注解处理.

如果Annotation Processor处理Annotation时(执行process方法)产生了新的Java代码,编译器会再调用一次Annotation Processor,如果第二次处理还有新代码产生,就会接着调用Annotation Processor,直到没有新代码产生为止。每执行一次process()方法被称为一个”round”,这样整个Annotation processing过程可以看作是一个round的序列。JSR 269主要被设计成为针对Tools或者容器的API。这个特性虽然在JavaSE 6已经存在,但是很少人知道它的存在。Java中的lombok就是使用这个特性实现编译期的代码插入的。另外,如果没有猜错,像IDEA在编写代码时候的标记语法错误的红色下划线也是通过这个特性实现的。KAPT(Annotation Processing for Kotlin),也就是Kotlin的编译也是通过此特性的。

Pluggable Annotation Processing API的核心是Annotation Processor即注解处理器,一般需要继承抽象类javax.annotation.processing.AbstractProcessor。注意,与运行时注解RetentionPolicy.RUNTIME不同,注解处理器只会处理编译期注解,也就是RetentionPolicy.SOURCE的注解类型,处理的阶段位于Java代码编译期间。

使用步骤

插件化注解处理API的使用步骤大概如下:

  • 1、自定义一个Annotation Processor,需要继承javax.annotation.processing.AbstractProcessor,并覆写process方法。
  • 2、自定义一个注解,注解的元注解需要指定@Retention(RetentionPolicy.SOURCE)
  • 3、需要在声明的自定义Annotation Processor中使用javax.annotation.processing.SupportedAnnotationTypes指定在第2步创建的注解类型的名称(注意需要全类名,”包名.注解类型名称”,否则会不生效)。
  • 4、需要在声明的自定义Annotation Processor中使用javax.annotation.processing.SupportedSourceVersion指定编译版本。
  • 5、可选操作,可以通在声明的自定义Annotation Processor中使用javax.annotation.processing.SupportedOptions指定编译参数。

实战例子

基础

下面我们模仿一下测试框架Junit里面的@Test注解,在运行时通过Annotation Processor获取到使用了自定义的@Test注解对应的方法的信息。因为如果想要动态修改一个类或者方法的代码内容,需要使用到字节码修改工具例如ASM等,这些操作过于深入,日后再谈。先定义一个注解:

  1. package club.throwable.processor;
  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. * @author throwable
  8. * @version v1.0
  9. * @description
  10. * @since 2018/5/27 11:18
  11. */
  12. @Target({ElementType.METHOD})
  13. @Retention(RetentionPolicy.SOURCE)
  14. public @interface Test {
  15. }

定义一个注解处理器:

  1. @SupportedAnnotationTypes(value = {"club.throwable.processor.Test"})
  2. @SupportedSourceVersion(value = SourceVersion.RELEASE_8)
  3. public class AnnotationProcessor extends AbstractProcessor {
  4. @Override
  5. public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  6. System.out.println("Log in AnnotationProcessor.process");
  7. for (TypeElement typeElement : annotations) {
  8. System.out.println(typeElement);
  9. }
  10. System.out.println(roundEnv);
  11. return true;
  12. }
  13. }

编写一个主类:

  1. public class Main {
  2. public static void main(String[] args) throws Exception{
  3. System.out.println("success");
  4. test();
  5. }
  6. @Test(value = "method is test")
  7. public static void test()throws Exception{
  8. }
  9. }

接着需要指定Processor,如果使用IDEA的话,Compiler->Annotation Processors中的Enable annotation processing必须勾选。然后可以通过下面几种方式指定指定Processor。

  • 1、直接使用编译参数指定,例如:javac -processor club.throwable.processor.AnnotationProcessor Main.java。
  • 2、通过服务注册指定,就是META-INF/services/javax.annotation.processing.Processor文件中添加club.throwable.processor.AnnotationProcessor。
  • 3、通过Maven的编译插件的配置指定如下:
  1. <plugin>
  2. <groupId>org.apache.maven.plugins</groupId>
  3. <artifactId>maven-compiler-plugin</artifactId>
  4. <version>3.5.1</version>
  5. <configuration>
  6. <source>1.8</source>
  7. <target>1.8</target>
  8. <encoding>UTF-8</encoding>
  9. <annotationProcessors>
  10. <annotationProcessor>
  11. club.throwable.processor.AnnotationProcessor
  12. </annotationProcessor>
  13. </annotationProcessors>
  14. </configuration>
  15. </plugin>

值得注意的是,以上三点生效的前提是club.throwable.processor.AnnotationProcessor已经被编译过,否则编译的时候就会报错:

  1. [ERROR] Bad service configuration file, or exception thrown while
  2. constructing Processor object: javax.annotation.processing.Processor:
  3. Provider club.throwable.processor.AnnotationProcessor not found

解决方法有两种,第一种是提前使用命令或者IDEA右键club.throwable.processor.AnnotationProcessor对它进行编译;第二种是把club.throwable.processor.AnnotationProcessor放到一个独立的Jar包引入。我在这里使用第一种方式解决。

最后,使用Maven命令mvn compile进行编译。输出如下:

  1. Log in AnnotationProcessor.process
  2. [errorRaised=false, rootElements=[club.throwable.processor.Test,club.throwable.processor.Main, club.throwable.processor.AnnotationProcessor, processingOver=false]
  3. Log in AnnotationProcessor.process
  4. [errorRaised=false, rootElements=[], processingOver=false]
  5. Log in AnnotationProcessor.process
  6. [errorRaised=false, rootElements=[], processingOver=true]

可见编译期间AnnotationProcessor生效了。

进阶

下面是一个例子直接修改类的代码,为实体类的Setter方法对应的属性生成一个Builder类,也就是原来的类如下:

  1. public class Person {
  2. private Integer age;
  3. private String name;
  4. public Integer getAge() {
  5. return age;
  6. }
  7. @Builder
  8. public void setAge(Integer age) {
  9. this.age = age;
  10. }
  11. public String getName() {
  12. return name;
  13. }
  14. @Builder
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. }

生成的Builder类如下:

  1. public class PersonBuilder {
  2. private Person object = new Person();
  3. public Person build() {
  4. return object;
  5. }
  6. public PersonBuilder setName(java.lang.String value) {
  7. object.setName(value);
  8. return this;
  9. }
  10. public PersonBuilder setAge(int value) {
  11. object.setAge(value);
  12. return this;
  13. }
  14. }

自定义的注解如下:

  1. @Target({ElementType.METHOD})
  2. @Retention(RetentionPolicy.SOURCE)
  3. public @interface Builder {
  4. }

自定义的注解处理器如下:

  1. import javax.annotation.processing.AbstractProcessor;
  2. import javax.annotation.processing.RoundEnvironment;
  3. import javax.annotation.processing.SupportedAnnotationTypes;
  4. import javax.annotation.processing.SupportedSourceVersion;
  5. import javax.lang.model.SourceVersion;
  6. import javax.lang.model.element.Element;
  7. import javax.lang.model.element.TypeElement;
  8. import javax.lang.model.type.ExecutableType;
  9. import javax.tools.Diagnostic;
  10. import javax.tools.JavaFileObject;
  11. import java.io.IOException;
  12. import java.io.PrintWriter;
  13. import java.util.List;
  14. import java.util.Map;
  15. import java.util.Set;
  16. import java.util.stream.Collectors;
  17. /**
  18. * @author throwable
  19. * @version v1.0
  20. * @description
  21. * @since 2018/5/27 11:21
  22. */
  23. @SupportedAnnotationTypes(value = {"club.throwable.processor.builder.Builder"})
  24. @SupportedSourceVersion(value = SourceVersion.RELEASE_8)
  25. public class BuilderProcessor extends AbstractProcessor {
  26. @Override
  27. public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  28. for (TypeElement typeElement : annotations) {
  29. Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(typeElement);
  30. Map<Boolean, List<Element>> annotatedMethods
  31. = annotatedElements.stream().collect(Collectors.partitioningBy(
  32. element -> ((ExecutableType) element.asType()).getParameterTypes().size() == 1
  33. && element.getSimpleName().toString().startsWith("set")));
  34. List<Element> setters = annotatedMethods.get(true);
  35. List<Element> otherMethods = annotatedMethods.get(false);
  36. otherMethods.forEach(element ->
  37. processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
  38. "@Builder must be applied to a setXxx method "
  39. + "with a single argument", element));
  40. Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(
  41. setter -> setter.getSimpleName().toString(),
  42. setter -> ((ExecutableType) setter.asType())
  43. .getParameterTypes().get(0).toString()
  44. ));
  45. String className = ((TypeElement) setters.get(0)
  46. .getEnclosingElement()).getQualifiedName().toString();
  47. try {
  48. writeBuilderFile(className, setterMap);
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. return true;
  54. }
  55. private void writeBuilderFile(
  56. String className, Map<String, String> setterMap)
  57. throws IOException {
  58. String packageName = null;
  59. int lastDot = className.lastIndexOf('.');
  60. if (lastDot > 0) {
  61. packageName = className.substring(0, lastDot);
  62. }
  63. String simpleClassName = className.substring(lastDot + 1);
  64. String builderClassName = className + "Builder";
  65. String builderSimpleClassName = builderClassName
  66. .substring(lastDot + 1);
  67. JavaFileObject builderFile = processingEnv.getFiler().createSourceFile(builderClassName);
  68. try (PrintWriter out = new PrintWriter(builderFile.openWriter())) {
  69. if (packageName != null) {
  70. out.print("package ");
  71. out.print(packageName);
  72. out.println(";");
  73. out.println();
  74. }
  75. out.print("public class ");
  76. out.print(builderSimpleClassName);
  77. out.println(" {");
  78. out.println();
  79. out.print(" private ");
  80. out.print(simpleClassName);
  81. out.print(" object = new ");
  82. out.print(simpleClassName);
  83. out.println("();");
  84. out.println();
  85. out.print(" public ");
  86. out.print(simpleClassName);
  87. out.println(" build() {");
  88. out.println(" return object;");
  89. out.println(" }");
  90. out.println();
  91. setterMap.forEach((methodName, argumentType) -> {
  92. out.print(" public ");
  93. out.print(builderSimpleClassName);
  94. out.print(" ");
  95. out.print(methodName);
  96. out.print("(");
  97. out.print(argumentType);
  98. out.println(" value) {");
  99. out.print(" object.");
  100. out.print(methodName);
  101. out.println("(value);");
  102. out.println(" return this;");
  103. out.println(" }");
  104. out.println();
  105. });
  106. out.println("}");
  107. }
  108. }
  109. }

主类如下:

  1. public class Main {
  2. public static void main(String[] args) throws Exception{
  3. //PersonBuilder在编译之后才会生成,这里需要编译后才能这样写
  4. Person person = new PersonBuilder().setAge(25).setName("doge").build();
  5. }
  6. }

先手动编译BuilderProcessor,然后在META-INF/services/javax.annotation.processing.Processor文件中添加club.throwable.processor.builder.BuilderProcessor,最后执行Maven命令mvn compile进行编译。

编译后控制台输出:

  1. [errorRaised=false, rootElements=[club.throwable.processor.builder.PersonBuilder], processingOver=false]

编译成功之后,target/classes包下面的club.throwable.processor.builder子包路径中会新增了一个类PersonBuilder

  1. package club.throwable.processor.builder;
  2. public class PersonBuilder {
  3. private Person object = new Person();
  4. public PersonBuilder() {
  5. }
  6. public Person build() {
  7. return this.object;
  8. }
  9. public PersonBuilder setName(String value) {
  10. this.object.setName(value);
  11. return this;
  12. }
  13. public PersonBuilder setAge(Integer value) {
  14. this.object.setAge(value);
  15. return this;
  16. }
  17. }

这个类就是编译期新增的。在这个例子中,编译期新增的类貌似没有什么作用。但是,如果像lombok那样对原来的实体类添加新的方法,那样的话就比较有用了。因为些类或者方法是编译期添加的,因此在代码中直接使用会标红。因此,lombok提供了IDEA或者eclipse的插件,插件的功能的也是用了插件式注解处理API。它是通过在AbstractProcessor.process方法中修改Javac 解析成的 AST抽象语法树来修改生成的java类。

小结

我在了解Pluggable Annotation Processing API的时候,通过搜索引擎搜索到的几乎都是安卓开发通过插件式注解处理API编译期动态添加代码等等的内容,可见此功能的使用还是比较广泛的。可能在文中的实战例子并不能体现Pluggable Annotation Processing API功能的强大,因此有时间可以基于此功能编写一些代码生成插件,例如下一篇将要介绍的lombok。

参考