Annotation-Processing-Tool详解

ShellaKowal 8年前
   <p>在这篇文章中我将阐述如何实现一个注解处理器。首先我将向你解释什么是注解处理器,你可以使用这个强大的工具来做什么及不能做什么。接下来我们将一步一步来实现一个简单的注解处理器。</p>    <h2>1. 一些基本概念</h2>    <p>在开始之前,我们需要声明一件重要的事情是:我们不是在讨论在<strong>运行时</strong>通过反射机制运行处理的注解,而是在讨论在<strong>编译时</strong>处理的注解。<br> 注解处理器是 javac 自带的一个工具,用来在编译时期扫描处理注解信息。你可以为某些注解注册自己的注解处理器。这里,我假设你已经了解什么是注解及如何自定义注解。如果你还未了解注解的话,可以查看<a href="/misc/goto?guid=4959626543625692747" rel="external">官方文档</a>。注解处理器在 Java 5 的时候就已经存在了,但直到 Java 6 (发布于2006看十二月)的时候才有可用的API。过了一段时间java的使用者们才意识到注解处理器的强大。所以最近几年它才开始流行。<br> 一个特定注解的处理器以 java 源代码(或者已编译的字节码)作为输入,然后生成一些文件(通常是<code>.java</code>文件)作为输出。那意味着什么呢?你可以生成 java 代码!这些 java 代码在生成的<code>.java</code>文件中。因此你不能改变已经存在的java类,例如添加一个方法。这些生成的 java 文件跟其他手动编写的 java 源代码一样,将会被 javac 编译。</p>    <h2>2. AbstractProcessor</h2>    <p>让我们来看一下处理器的 API。所有的处理器都继承了<code>AbstractProcessor</code>,如下所示:</p>    <pre>  <code class="language-java">package com.example;    import java.util.LinkedHashSet;  import java.util.Set;  import javax.annotation.processing.AbstractProcessor;  import javax.annotation.processing.ProcessingEnvironment;  import javax.annotation.processing.RoundEnvironment;  import javax.annotation.processing.SupportedAnnotationTypes;  import javax.annotation.processing.SupportedSourceVersion;  import javax.lang.model.SourceVersion;  import javax.lang.model.element.TypeElement;    public class MyProcessor extends AbstractProcessor {     @Override   public boolean process(Set<? extends TypeElement> annoations,     RoundEnvironment env) {    return false;   }     @Override   public Set<String> getSupportedAnnotationTypes() {    Set<String> annotataions = new LinkedHashSet<String>();       annotataions.add("com.example.MyAnnotation");       return annotataions;   }     @Override   public SourceVersion getSupportedSourceVersion() {    return SourceVersion.latestSupported();   }     @Override   public synchronized void init(ProcessingEnvironment processingEnv) {    super.init(processingEnv);   }    }</code></pre>    <ul>     <li> <p><code>init(ProcessingEnvironment processingEnv)</code> :所有的注解处理器类<strong>都必须有一个无参构造函数</strong>。然而,有一个特殊的方法<code>init()</code>,它会被注解处理工具调用,以<code>ProcessingEnvironment</code>作为参数。ProcessingEnvironment 提供了一些实用的工具类<code>Elements</code>, <code>Types</code>和<code>Filer</code>。我们在后面将会使用到它们。</p> </li>     <li> <p><code>process(Set<? extends TypeElement> annoations, RoundEnvironment env)</code> :这类似于每个处理器的<code>main()</code>方法。你可以在这个方法里面编码实现扫描,处理注解,生成 java 文件。使用<code>RoundEnvironment</code> 参数,你可以查询被特定注解标注的元素(原文:you can query for elements annotated with a certain annotation )。后面我们将会看到详细内容。</p> </li>     <li> <p><code>getSupportedAnnotationTypes()</code>:在这个方法里面你必须指定哪些注解应该被注解处理器注册。注意,它的返回值是一个<code>String</code>集合,包含了你的注解处理器想要处理的注解类型的全称。换句话说,你在这里定义你的注解处理器要处理哪些注解。</p> </li>     <li> <p><code>getSupportedSourceVersion()</code> : 用来指定你使用的 java 版本。通常你应该返回<code>SourceVersion.latestSupported()</code> 。不过,如果你有足够的理由坚持用 java 6 的话,你也可以返回<code>SourceVersion.RELEASE_6</code>。我建议使用<code>SourceVersion.latestSupported()</code>。在 Java 7 中,你也可以使用注解的方式来替代重写<code>getSupportedAnnotationTypes()</code> 和 <code>getSupportedSourceVersion()</code>,如下所示:</p> <pre>  <code class="language-java">@SupportedSourceVersion(value=SourceVersion.RELEASE_7)  @SupportedAnnotationTypes({     // Set of full qullified annotation type names   "com.example.MyAnnotation",   "com.example.AnotherAnnotation"   })  public class MyProcessor extends AbstractProcessor {     @Override   public boolean process(Set<? extends TypeElement> annoations,     RoundEnvironment env) {    return false;   }   @Override   public synchronized void init(ProcessingEnvironment processingEnv) {    super.init(processingEnv);   }  }</code></pre> <p> </p> </li>    </ul>    <p>由于兼容性问题,特别是对于 android ,我建议重写<code>getSupportedAnnotationTypes()</code> 和 <code>getSupportedSourceVersion()</code> ,而不是使用 <code>@SupportedAnnotationTypes</code> 和 <code>@SupportedSourceVersion</code>。</p>    <p>接下来你必须知道的事情是:注解处理器运行在它自己的 JVM 中。是的,你没看错。javac 启动了一个完整的 java 虚拟机来运行注解处理器。这意味着什么?你可以使用任何你在普通 java 程序中使用的东西。使用 <code>guava</code>! 你可以使用依赖注入工具,比如<code>dagger</code>或者任何其他你想使用的类库。但不要忘记,即使只是一个小小的处理器,你也应该注意使用高效的算法及设计模式,就像你在开发其他 java 程序中所做的一样。</p>    <h2>3. 注册你的处理器</h2>    <p>你可能会问 “怎样注册我的注解处理器到 javac ?”。你必须提供一个<code>.jar</code>文件。就像其他 .jar 文件一样,你将你已经编译好的注解处理器打包到此文件中。并且,在你的 .jar 文件中,你必须打包一个特殊的文件<code>javax.annotation.processing.Processor</code>到<code>META-INF/services</code>目录下。因此你的 .jar 文件目录结构看起来就你这样:</p>    <pre>  <code class="language-java">MyProcess.jar   -com    -example     -MyProcess.class   -META-INF    -services     -javax.annotation.processing.Processor</code></pre>    <p><code>javax.annotation.processing.Processor</code> 文件的内容是一个列表,每一行是一个注解处理器的全称。例如:</p>    <pre>  <code class="language-java">com.example.MyProcess  com.example.AnotherProcess</code></pre>    <h2>4. 例子:工厂模式</h2>    <p>现在可以举一个实际的例子了。我们使用<code>maven</code> 工具来作为我们的编译系统和依赖管理工具。我会把例子的代码放到 <a href="/misc/goto?guid=4959626544105582548" rel="external"><code>github</code></a>上。<br> 首先,我必须要说的是,想要找到一个可以使用注解处理器去解决的简单问题来当作教程,并不是一件容易的事。这篇教程中,我们将实现一个非常简单的工厂模式(不是抽象工厂模式)。它只是为了给你简明的介绍注解处理器的API而已。所以这个问题的程序,并不是那么有用,也不是一个真实开发中的例子。再次声明,你能学到的只是注解处理器的相关内容,而不是设计模式。</p>    <p>我们要解决的问题是:我们要实现一个 pizza 店,这个 pizza 店提供给顾客两种 pizza (Margherita 和 Calzone),还有甜点 Tiramisu(提拉米苏)。<br> 简单看一下这段代码:<br> <code>Meal.java</code>:</p>    <pre>  <code class="language-java">package com.example.pizza;    public interface Meal {   public float getPrice();  }</code></pre>    <p><code>MargheritaPizza.java</code>:</p>    <pre>  <code class="language-java">package com.example.pizza;    public class MargheritaPizza implements Meal{   @Override   public float getPrice() {    return 6.0f;   }  }</code></pre>    <p><code>CalzonePizza.java</code>:</p>    <pre>  <code class="language-java">package com.example.pizza;    public class CalzonePizza implements Meal{   @Override   public float getPrice() {    return 8.5f;   }  }</code></pre>    <p><code>Tiramisu.java</code>:</p>    <pre>  <code class="language-java">package com.example.pizza;    public class Tiramisu implements Meal{   @Override   public float getPrice() {    return 4.5f;   }  }</code></pre>    <p>顾客要在我们的 pizza 店购买食物的话,就得输入食物的名称:<br> <code>PizzaStore.java</code>:</p>    <pre>  <code class="language-java">package com.example.pizza;    import java.util.Scanner;    public class PizzaStore {     public Meal order(String mealName) {    if (null == mealName) {     throw new IllegalArgumentException("name of meal is null!");    }    if ("Margherita".equals(mealName)) {     return new MargheritaPizza();    }      if ("Calzone".equals(mealName)) {     return new CalzonePizza();    }      if ("Tiramisu".equals(mealName)) {     return new Tiramisu();    }      throw new IllegalArgumentException("Unknown meal '" + mealName + "'");   }     private static String readConsole() {    Scanner scanner = new Scanner(System.in);    String meal = scanner.nextLine();    scanner.close();    return meal;   }      public static void main(String[] args) {    System.out.println("welcome to pizza store");    PizzaStore pizzaStore = new PizzaStore();    Meal meal = pizzaStore.order(readConsole());    System.out.println("Bill:$" + meal.getPrice());   }  }</code></pre>    <p>正如你所见,在<code>order()</code>方法中,我们有许多 if 条件判断语句。并且,如果我们添加一种新的 pizza 的话,我们就得添加一个新的 if 条件判断。但是等一下,使用注解处理器和工厂模式,我们可以让一个注解处理器生成这些 if 语句。如此一来,我们想要的代码就像这样子:<br> <code>PizzaStore.java</code>:</p>    <pre>  <code class="language-java">package com.example.pizza;    import java.util.Scanner;    public class PizzaStore {     private MealFactory factory = new MealFactory();      public Meal order(String mealName) {    return factory.create(mealName);   }     private static String readConsole() {    Scanner scanner = new Scanner(System.in);    String meal = scanner.nextLine();    scanner.close();    return meal;   }      public static void main(String[] args) {    System.out.println("welcome to pizza store");    PizzaStore pizzaStore = new PizzaStore();    Meal meal = pizzaStore.order(readConsole());    System.out.println("Bill:$" + meal.getPrice());   }  }</code></pre>    <p><code>MealFactory</code> 类应该是这样的:<br> <code>MealFactory.java</code>:</p>    <pre>  <code class="language-java">package com.example.pizza;    public class MealFactory {     public Meal create(String id) {    if (id == null) {     throw new IllegalArgumentException("id is null!");    }    if ("Calzone".equals(id)) {     return new CalzonePizza();    }      if ("Tiramisu".equals(id)) {     return new Tiramisu();    }      if ("Margherita".equals(id)) {     return new MargheritaPizza();    }      throw new IllegalArgumentException("Unknown id = " + id);   }  }</code></pre>    <h2>5. @Factory Annotation</h2>    <p>能猜到么,我们打算使用注解处理器生成<code>MealFactory</code>类。更一般的说,我们想要提供一个注解和一个处理器用来生成工厂类。<br> 让我们看一下<code>@Factory</code>注解:<br> <code>Factory.java</code>:</p>    <pre>  <code class="language-java">package com.example.apt;    import java.lang.annotation.ElementType;  import java.lang.annotation.Retention;  import java.lang.annotation.RetentionPolicy;  import java.lang.annotation.Target;    @Target(ElementType.TYPE)  @Retention(RetentionPolicy.CLASS)  public @interface Factory {     /**    * The name of the factory    */   Class<?> type();     /**    * The identifier for determining which item should be instantiated    */   String id();  }</code></pre>    <p> </p>    <p>思想是这样的:我们注解那些食物类,使用<code>type()</code>表示这个类属于哪个工厂,使用<code>id()</code>表示这个类的具体类型。让我们将<code>@Factory</code>注解应用到这些类上吧:<br> <code>MargheritaPizza.java</code>:</p>    <pre>  <code class="language-java">package com.example.pizza;    import com.example.apt.Factory;    @Factory(type=MargheritaPizza.class, id="Margherita")  public class MargheritaPizza implements Meal{     @Override   public float getPrice() {    return 6.0f;   }  }</code></pre>    <p><code>CalzonePizza.java</code>:</p>    <pre>  <code class="language-java">package com.example.pizza;    import com.example.apt.Factory;    @Factory(type=CalzonePizza.class, id="Calzone")  public class CalzonePizza implements Meal{     @Override   public float getPrice() {    return 8.5f;   }  }</code></pre>    <p><code>Tiramisu.java</code>:</p>    <pre>  <code class="language-java">package com.example.pizza;    import com.example.apt.Factory;    @Factory(type=Tiramisu.class, id="Tiramisu")  public class Tiramisu implements Meal{     @Override   public float getPrice() {    return 4.5f;   }  }</code></pre>    <p> </p>    <p> </p>    <p> </p>    <p>你可能会问,我们是不是可以只将<code>@Factory</code>注解应用到<code>Meal</code>接口上?答案是不行,因为注解是不能被继承的。即在<code>class X</code>上有注解,<code>class Y extends X</code>,那么<code>class Y</code>是不会继承<code>class X</code>上的注解的。在我们编写处理器之前,需要明确几点规则:</p>    <ol>     <li>只有类能够被<code>@Factory</code>注解,因为接口和虚类是不能通过<code>new</code>操作符实例化的。</li>     <li>被<code>@Factory</code>注解的类必须提供一个默认的无参构造函数。否则,我们不能实例化一个对象。</li>     <li>被<code>@Factory</code>注解的类必须直接继承或者间接继承<code>type</code>指定的类型。(或者实现它,如果<code>type</code>指定的是一个接口)</li>     <li>被<code>@Factory</code>注解的类中,具有相同的<code>type</code>类型的话,这些类就会被组织起来生成一个工厂类。工厂类以<code>Factory</code>作为后缀,例如:<code>type=Meal.class</code>将会生成<code>MealFactory</code>类。</li>     <li><code>id</code>的值只能是字符串,且在它的<code>type</code>组中必须是唯一的。</li>    </ol>    <h2>6. 注解处理器</h2>    <p>我将会通过添加一段代码接着解释这段代码的方法,一步一步引导你。三个点号(<code>...</code>)表示省略那部分前面已经讨论过或者将在后面讨论的代码。目的就是为了让代码片段更具有可读性。前面已经说过,我们的完整代码将放到<code>github</code>上。OK,让我们开始编写我们的<code>FactoryProcessor</code>的框架吧:<br> <code>FactoryProcessor.java</code>:</p>    <pre>  <code class="language-java">package com.example.apt;    import java.util.LinkedHashMap;  import java.util.LinkedHashSet;  import java.util.Map;  import java.util.Set;  import javax.annotation.processing.AbstractProcessor;  import javax.annotation.processing.Filer;  import javax.annotation.processing.Messager;  import javax.annotation.processing.ProcessingEnvironment;  import javax.annotation.processing.RoundEnvironment;  import javax.lang.model.SourceVersion;  import javax.lang.model.element.TypeElement;  import javax.lang.model.util.Elements;  import javax.lang.model.util.Types;    public class FactoryProcessor extends AbstractProcessor {     private Types typeUtils;   private Elements elementUtils;   private Filer filer;   private Messager messager;   private Map<String, FactoryGroupedClasses> factoryClasses =      new LinkedHashMap<String, FactoryGroupedClasses>();     @Override   public synchronized void init(ProcessingEnvironment processingEnv) {    super.init(processingEnv);    typeUtils = processingEnv.getTypeUtils();       elementUtils = processingEnv.getElementUtils();       filer = processingEnv.getFiler();       messager = processingEnv.getMessager();   }     @Override   public boolean process(Set<? extends TypeElement> arg0,     RoundEnvironment arg1) {    ...    return false;   }     @Override   public Set<String> getSupportedAnnotationTypes() {    Set<String> annotataions = new LinkedHashSet<String>();       annotataions.add(Factory.class.getCanonicalName());       return annotataions;   }     @Override   public SourceVersion getSupportedSourceVersion() {    return SourceVersion.latestSupported();   }  }</code></pre>    <p>在<code>getSupportedAnnotationTypes()</code>方法中,我们指定<code>@Factory</code>注解将被这个处理器处理。</p>    <h2>7. Elements and TypeMirrors</h2>    <p>在<code>init()</code>方法中,我们使用了以下类型:</p>    <ul>     <li>Elements:一个用来处理<code>Element</code>的工具类(后面详细说明)</li>     <li>Types:一个用来处理<code>TypeMirror</code>的工具类(后面详细说明)</li>     <li>Filer:正如这个类的名字所示,你可以使用这个类来创建文件</li>    </ul>    <p>在注解处理器中,我们扫描 java 源文件,源代码中的每一部分都是<code>Element</code>的一个特定类型。换句话说:<code>Element</code>代表程序中的元素,比如说 包,类,方法。每一个元素代表一个静态的,语言级别的结构。在下面的例子中,我将添加注释来说明这个问题:</p>    <pre>  <code class="language-java">package com.example;    public class Foo { // TypeElement     private int a; // VariableElement   private Foo other; // VariableElement     public Foo() {} // ExecuteableElement     public void setA( // ExecuteableElement     int newA // TypeElement   ) {   }  }</code></pre>    <p>你得换个角度来看源代码。它只是结构化的文本而已。它不是可以执行的。你可以把它当作 你试图去解析的XML 文件。或者一棵编译中创建的抽象语法树。就像在 XML 解析器中,有许多DOM元素。你可以通过一个元素找到它的父元素或者子元素。<br> 例如:如果你有一个代表<code>public class Foo</code>的<code>TypeElement</code>,你就可以迭代访问它的子结点:</p>    <pre>  <code class="language-java">TypeElement fooClass = ... ;  for (Element e : fooClass.getEnclosedElements()){ // iterate over children   Element parent = e.getEnclosingElement();  // parent == fooClass  }</code></pre>    <p>如你所见,<code>Elements</code>代表源代码,<code>TypeElement</code>代表源代码中的元素类型,例如类。然后,<code>TypeElement</code>并不包含类的相关信息。你可以从<code>TypeElement</code>获取类的名称,但你不能获取类的信息,比如说父类。这些信息可以通过<code>TypeMirror</code>获取。你可以通过调用<code>element.asType()</code>来获取一个<code>Element</code>的<code>TypeMirror</code>。</p>    <p>(译注:关于<code>getEnclosedElements</code>, <code>getEnclosingElement</code> 的解释,参见<a href="/misc/goto?guid=4959676356587396769" rel="external">官方文档</a>)</p>    <h2>8. Searching For @Factory</h2>    <p>让我们一步一步来实现<code>process()</code>方法吧。首先我们扫描所有被<code>@Factory</code>注解的类:</p>    <pre>  <code class="language-java">@Override  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {   for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Factory.class)) {    ...   }   return false;  }</code></pre>    <p>这里并没有什么高深的技术。<code>roundEnv.getElementsAnnotatedWith(Factory.class)</code> 返回一个被<code>@Factory</code>注解的元素列表。你可能注意到我避免说“返回一个被<code>@Factory</code>注解的类列表”。因为它的确是返回了一个<code>Element</code>列表。记住:<code>Element</code>可以是类,方法,变量等。所以,我们下一步需要做的是检查这个元素是否是一个类:</p>    <pre>  <code class="language-java">@Override  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {   for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Factory.class)) {    if(annotatedElement.getKind() != ElementKind.CLASS) {     ...       }   }   return false;  }</code></pre>    <p> </p>    <p> </p>    <p> </p>    <p>为什么需要这样做呢?因为我们要确保只有<strong>class</strong>类型的元素被我们的处理器处理。前面我们已经学过,类是一种<code>TypeElement</code>元素。那我们为什么不使用<code>if (! (annotatedElement instanceof TypeElement))</code>来检查呢?这是错误的判断,因为接口也是一种<code>TypeElement</code>类型。所以在注解处理器中,你应该避免使用<code>instanceof</code>,应该用<code>ElementKind</code>或者配合<code>TypeMirror</code>使用<code>TypeKind</code>。</p>    <h2>9. 错误处理</h2>    <p>在<code>init()</code>方法中,我们也获取了一个<code>Messager</code>的引用。<code>Messager</code>为注解处理器提供了一种报告错误消息,警告信息和其他消息的方式。它不是注解处理器开发者的日志工具。<code>Messager</code>是用来给那些使用了你的注解处理器的第三方开发者显示信息的。在<a href="/misc/goto?guid=4959626543795406138" rel="external">官方文档</a>中描述了不同级别的信息。非常重要的是<code>Kind.ERROR</code>,因为这种消息类型是用来表明我们的注解处理器在处理过程中出错了。有可能是第三方开发者误使用了我们的<code>@Factory</code>注解(比如,使用<code>@Factory</code>注解了一个接口)。这个概念与传统的 java 应用程序有一点区别。传统的 java 应用程序出现了错误,你可以抛出一个异常。如果你在<code>process()</code>中抛出了一个异常,那 jvm 就会崩溃。注解处理器的使用者将会得到一个从 javac 给出的非常难懂的异常错误信息。因为它包含了注解处理器的堆栈信息。因此注解处理器提供了<code>Messager</code>类。它能打印漂亮的错误信息,而且你可以链接到引起这个错误的元素上。在现代的IDE中,第三方开发者可以点击错误信息,IDE会跳转到产生错误的代码行中,以便快速定位错误。<br> 回到<code>process()</code>方法的实现。如果用户将<code>@Factory</code>注解到了一个非<code>class</code>的元素上,我们就抛出一个错误信息:</p>    <pre>  <code class="language-java">@Override  public boolean process(Set<? extends TypeElement> annotations,    RoundEnvironment roundEnv) {   for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(Factory.class)) {    if(annotatedElement.getKind() != ElementKind.CLASS) {     error(annotatedElement, "Only classes can be annotated with @%s",                Factory.class.getSimpleName());     return true; // Exit processing    }      }   return false;  }    private void error(Element e, String msg, Object... args) {      messager.printMessage(       Diagnostic.Kind.ERROR,       String.format(msg, args),       e);    }</code></pre>    <p>为了能够获取<code>Messager</code>显示的信息,非常重要的是注解处理器必须不崩溃地完成运行。这就是我们在调用<code>error()</code>后执行<code>return true</code>的原因。如果我们在这里没有返回的话,<code>process()</code>就会继续运行,因为<code>messager.printMessage( Diagnostic.Kind.ERROR)</code>并不会终止进程。如果我们没有在打印完错误信息后返回的话,我们就可能会运行到一个空指针异常等等。就像前面所说的,如果我们继续运行<code>process()</code>,一旦有处理的异常在<code>process()</code>中被抛出,javac 就会打印注解处理器的空指针异常堆栈信息,而不是<code>Messager</code>显示的信息。</p>    <h2>10. 数据模型</h2>    <p>在我们继续检查被<code>@Factory</code>注解的类是否满足我们前面所说的五条规则之前,我们先介绍一个数据结构,它能让我们更方便的继续处理接下来的工作。有时候问题或者处理器看起来太过简单了,导致一些程序员倾向于用面向过程的方法编写整个处理器。但你知道吗?一个注解处理器仍然是一个 java 程序。所以我们应该使用面向对象,接口,设计模式以及任何你可能在其他普通Java程序中使用的技巧。<br> 虽然我们的<code>FactoryProcessor</code>非常简单,但是我们仍然想将一些信息作为对象保存。在<code>FactoryAnnotationClass</code>中,我们保存被注解的类的数据,比如合法的类名以及<code>@Factory</code>注解本身的一些数据。所以,我们保存<code>TypeElement</code>和处理过的<code>@Factory</code>注解:<br> <code>FactoryAnnotationClass.java</code>:</p>    <pre>  <code class="language-java">package com.example.apt;    import javax.lang.model.element.TypeElement;  import javax.lang.model.type.DeclaredType;  import javax.lang.model.type.MirroredTypeException;    public class FactoryAnnotatedClass {     private TypeElement annotatedClassElement;   private String qualifiedSuperClassName;   private String simpleTypeName;   private String id;     public FactoryAnnotatedClass(TypeElement classElement) throws IllegalArgumentException {    this.annotatedClassElement = classElement;    Factory annotation = classElement.getAnnotation(Factory.class);    id = annotation.id();      if ("".equals(id)) {     throw new IllegalArgumentException(       String.format(         "id() in @%s for class %s is null or empty! that's not allowed",         Factory.class.getSimpleName(),          classElement.getQualifiedName().toString()));    }      // Get the full QualifiedTypeName    try {     Class<?> clazz = annotation.type();     qualifiedSuperClassName = clazz.getCanonicalName();     simpleTypeName = clazz.getSimpleName();    } catch (MirroredTypeException mte) {     DeclaredType classTypeMirror = (DeclaredType) mte.getTypeMirror();     TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();     qualifiedSuperClassName = classTypeElement.getQualifiedName().toString();     simpleTypeName = classTypeElement.getSimpleName().toString();    }   }     /**    * Get the id as specified in {@link Factory#id()}. return the id    */   public String getId() {    return id;   }     /**    * Get the full qualified name of the type specified in    * {@link Factory#type()}.    *     * @return qualified name    */   public String getQualifiedFactoryGroupName() {    return qualifiedSuperClassName;   }     /**    * Get the simple name of the type specified in {@link Factory#type()}.    *     * @return qualified name    */   public String getSimpleFactoryGroupName() {    return simpleTypeName;   }     /**    * The original element that was annotated with @Factory    */   public TypeElement getTypeElement() {    return annotatedClassElement;   }  }</code></pre>    <p>看起来有很多代码,但是最重要的代码在构造函数中,你可以看到如下的代码:</p>    <pre>  <code class="language-java">Factory annotation = classElement.getAnnotation(Factory.class);    id = annotation.id();      if ("".equals(id)) {     throw new IllegalArgumentException(       String.format(         "id() in @%s for class %s is null or empty! that's not allowed",         Factory.class.getSimpleName(),          classElement.getQualifiedName().toString()));    }</code></pre>    <p>这里,我们获取<code>@Factory</code>注解,并检查<code>id</code>是否为空。如果<code>id</code>为空,我们将会抛出一个<code>IllegalArgumentException</code>异常。你可能感到疑惑的是,前面我们说了不要抛出异常,而是使用Messager。但这并不矛盾。我们在这里抛出一个内部异常,后面你将会看到我们在<code>process()</code>中捕获了这个异常。我们有两个这样做的理由:</p>    <ol>     <li> <p>我想说明你应该仍然像普通的Java程序一样编码。抛出和捕获异常被认为是一个好的Java编程实践。</p> </li>     <li> <p>如果我们想要在FactoryAnnotatedClass中正确地打印信息,我们也需要传入Messager对象,就像我们在错误处理一节中已经提到的,注解处理器必须成功结束,才能让<code>Messager</code>打印错误信息。如果我们想使用<code>Messager</code>打印一个错误信息,我们应该怎样通知<code>process()</code>发生了一个错误?最简单的方法,并且我认为了直观的方法,就是抛出一个异常然后让步<code>process()</code>捕获它。</p> </li>    </ol>    <p>接下来,我们将获取<code>@Fractory</code>注解中的<code>type</code>成员域。我们比较感兴趣的是合法的全名:</p>    <pre>  <code class="language-java">// Get the full QualifiedTypeName  try {   Class<?> clazz = annotation.type();   qualifiedSuperClassName = clazz.getCanonicalName();   simpleTypeName = clazz.getSimpleName();  } catch (MirroredTypeException mte) {   DeclaredType classTypeMirror = (DeclaredType) mte.getTypeMirror();   TypeElement classTypeElement = (TypeElement) classTypeMirror.asElement();   qualifiedSuperClassName = classTypeElement.getQualifiedName().toString();   simpleTypeName = classTypeElement.getSimpleName().toString();  }</code></pre>    <p>这有点棘手,因为这里的类型是<code>java.lang.Class</code>。那意味着,这是一个真实的<code>Class</code>对象。因为注解处理器在编译 java 源码之前执行,所以我们必须得考虑两种情况:</p>    <ol>     <li>这个类已经被编译过了:这种情况是第三方 .jar 包含已编译的被<code>@Factory</code>注解 .class 文件。这种情况下,我们可以像<code>try</code> 代码块中所示那样直接获取Class。 (译注:因为<code>@Factory</code>的<code>@Retention</code>为<code>RetentionPolicy.CLASS</code>,所有被编译过的代码也会保留<code>@Factory</code>的注解信息)</li>     <li>这个类还没有被编译:这种情况是我们尝试编译被<code>@Fractory</code>注解的源代码。这种情况下,直接获取<code>Class</code>会抛出<code>MirroredTypeException</code>异常。幸运的是,<code>MirroredTypeException</code>包含一个<code>TypeMirror</code>,它表示我们未被编译类。因为我们知道它一定是一个<code>Class</code>类型(我们前面有检查过),所以我们可以将它转换为<code>DeclaredType</code>, 然后获取<code>TypeElement</code>来读取合法名称。</li>    </ol>    <p>好了,我们还需要一个叫<code>FactoryGroupedClasses</code>的数据结构,用来简单的组合所有的<code>FactoryAnnotatedClasses</code>到一起。</p>    <pre>  <code class="language-java">package com.example.apt;    import java.io.IOException;  import java.util.LinkedHashMap;  import java.util.Map;    import javax.annotation.processing.Filer;  import javax.lang.model.util.Elements;    public class FactoryGroupedClasses {     private String qualifiedClassName;     private Map<String, FactoryAnnotatedClass> itemsMap = new LinkedHashMap<String, FactoryAnnotatedClass>();     public FactoryGroupedClasses(String qualifiedClassName) {    this.qualifiedClassName = qualifiedClassName;   }     public void add(FactoryAnnotatedClass toInsert)     throws IdAlreadyUsedException {      FactoryAnnotatedClass existing = itemsMap.get(toInsert.getId());    if (existing != null) {     throw new IdAlreadyUsedException(existing);    }      itemsMap.put(toInsert.getId(), toInsert);   }     public void generateCode(Elements elementUtils, Filer filer)     throws IOException {    ...   }  }</code></pre>    <p>如你所见,它只是一个基本的<code>Map<String, FactoryAnnotatedClass></code>,这个<code>map</code>用来映射<code>@Factory.id()</code>到<code>FactoryAnnotatedClass</code>。我们选择使用<code>Map</code>,是因为我们想确保每一个<code>id</code>都的唯一的。使用<code>map</code>查找,这可以很容易实现。<code>generateCode()</code>将会被调用来生成工厂在的代码(稍后讨论)。</p>    <h2>11. 匹配准则</h2>    <p>让我们来继续实现<code>process()</code>方法。接下来我们要检查被注解的类至少有一个公有构造函数,不是抽象类,继承了特定的类,以及是一个<code>public</code>类:</p>    <pre>  <code class="language-java">@Override  public boolean process(Set<? extends TypeElement> annotations,    RoundEnvironment roundEnv) {   for (Element annotatedElement : roundEnv     .getElementsAnnotatedWith(Factory.class)) {    if (annotatedElement.getKind() != ElementKind.CLASS) {     error(annotatedElement,       "Only classes can be annotated with @%s",       Factory.class.getSimpleName());     return true; // Exit processing    }      // We can cast it, because we know that it of ElementKind.CLASS    TypeElement typeElement = (TypeElement) annotatedElement;      try {     FactoryAnnotatedClass annotatedClass = new FactoryAnnotatedClass(       typeElement); // throws IllegalArgumentException       if (!isValidClass(annotatedClass)) {      return true; // Error message printed, exit processing     }    } catch (IllegalArgumentException e) {     // @Factory.id() is empty     error(typeElement, e.getMessage());     return true;    }    ...   }   return false;  }    private boolean isValidClass(FactoryAnnotatedClass item) {     // Cast to TypeElement, has more type specific methods   TypeElement classElement = item.getTypeElement();     if (!classElement.getModifiers().contains(Modifier.PUBLIC)) {    error(classElement, "The class %s is not public.", classElement      .getQualifiedName().toString());    return false;   }     // Check if it's an abstract class   if (classElement.getModifiers().contains(Modifier.ABSTRACT)) {    error(classElement,      "The class %s is abstract. You can't annotate abstract classes with @%",      classElement.getQualifiedName().toString(),      Factory.class.getSimpleName());    return false;   }     // Check inheritance: Class must be childclass as specified in   // @Factory.type();   TypeElement superClassElement = elementUtils.getTypeElement(item     .getQualifiedFactoryGroupName());   if (superClassElement.getKind() == ElementKind.INTERFACE) {    // Check interface implemented    if (!classElement.getInterfaces().contains(      superClassElement.asType())) {     error(classElement,       "The class %s annotated with @%s must implement the interface %s",       classElement.getQualifiedName().toString(),       Factory.class.getSimpleName(),       item.getQualifiedFactoryGroupName());     return false;    }   } else {    // Check subclassing    TypeElement currentClass = classElement;    while (true) {     TypeMirror superClassType = currentClass.getSuperclass();       if (superClassType.getKind() == TypeKind.NONE) {      // Basis class (java.lang.Object) reached, so exit      error(classElement,        "The class %s annotated with @%s must inherit from %s",        classElement.getQualifiedName().toString(),        Factory.class.getSimpleName(),        item.getQualifiedFactoryGroupName());      return false;     }       if (superClassType.toString().equals(       item.getQualifiedFactoryGroupName())) {      // Required super class found      break;     }       // Moving up in inheritance tree     currentClass = (TypeElement) typeUtils       .asElement(superClassType);    }   }   // Check if an empty public constructor is given   for (Element enclosed : classElement.getEnclosedElements()) {    if (enclosed.getKind() == ElementKind.CONSTRUCTOR) {     ExecutableElement constructorElement = (ExecutableElement) enclosed;     if (constructorElement.getParameters().size() == 0       && constructorElement.getModifiers().contains(         Modifier.PUBLIC)) {      // Found an empty constructor      return true;     }    }   }     // No empty constructor found   error(classElement,     "The class %s must provide an public empty default constructor",     classElement.getQualifiedName().toString());   return false;  }</code></pre>    <p>我们添加了一个<code>isValidClass()</code>方法,它检查是否我们所有的规则都被满足了:</p>    <ul>     <li>类必须是<code>public</code>的:<code>classElement.getModifiers().contains(Modifier.PUBLIC)</code></li>     <li>类不能是抽象的:<code>classElement.getModifiers().contains(Modifier.ABSTRACT)</code></li>     <li>类必须是<code>@Factoy.type()</code>指定的类型的子类或者接口的实现:首先,我们使用<code>elementUtils.getTypeElement(item.getQualifiedFactoryGroupName())</code>来创建一个元素。没错,你可以创建一个<code>TypeElement</code>(使用<code>TypeMirror</code>),只要你知道合法的类名称。然后我们检查它是一个接口还是一个类:<code>superClassElement.getKind() == ElementKind.INTERFACE</code>。有两种情况:如果它是一个接口,就判断<code>classElement.getInterfaces().contains(superClassElement.asType())</code>。如果是类,我们就必须使用<code>currentClass.getSuperclass()</code>扫描继承树。注意,整个检查也可以使用<code>typeUtils.isSubtype()</code>来实现。</li>     <li>类必须有一个<code>public</code>的无参构造函数:我们遍历所有该类直接封装的元素<code>classElement.getEnclosedElements()</code>,然后检查<code>ElementKind.CONSTRUCTOR</code>,<code>Modifier.PUBLIC</code> 和<code>constructorElement.getParameters().size() == 0</code></li>    </ul>    <p>如果以上这些条件全都满足,则<code>isValidClass()</code>返回 <code>true</code>,否则,它打印一个错误信息然后返回 <code>false</code>。</p>    <h2>11. 组合被注解的类</h2>    <p>一旦我们检查<code>isValidClass()</code>成功,我们就继续添加<code>FactoryAnnotatedClass</code>到相应的<code>FactoryGroupedClasses</code>中,如下所示:</p>    <pre>  <code class="language-java">public boolean process(Set<? extends TypeElement> annotations,    RoundEnvironment roundEnv) {   for (Element annotatedElement : roundEnv     .getElementsAnnotatedWith(Factory.class)) {     ...    try {     FactoryAnnotatedClass annotatedClass = new FactoryAnnotatedClass(       typeElement); // throws IllegalArgumentException       if (!isValidClass(annotatedClass)) {      return true; // Error message printed, exit processing     }       // Everything is fine, so try to add     FactoryGroupedClasses factoryClass = factoryClasses       .get(annotatedClass.getQualifiedFactoryGroupName());     if (factoryClass == null) {      String qualifiedGroupName = annotatedClass        .getQualifiedFactoryGroupName();      factoryClass = new FactoryGroupedClasses(qualifiedGroupName);      factoryClasses.put(qualifiedGroupName, factoryClass);     }       // Throws IdAlreadyUsedException if id is conflicting with     // another @Factory annotated class with the same id     factoryClass.add(annotatedClass);    } catch (IllegalArgumentException e) {     // @Factory.id() is empty --> printing error message     error(typeElement, e.getMessage());     return true;    } catch (IdAlreadyUsedException e) {     FactoryAnnotatedClass existing = e.getExisting();     // Already existing     error(annotatedElement,       "Conflict: The class %s is annotated with @%s with id ='%s' but %s already uses the same id",       typeElement.getQualifiedName().toString(),       Factory.class.getSimpleName(), existing         .getTypeElement().getQualifiedName().toString());     return true;    }   ...</code></pre>    <h2>12. 代码生成</h2>    <p>我们已经收集了所有被<code>@Factory</code>注解的类的信息,这些信息以<code>FactoryAnnotatedClass</code>的形式保存在<code>FactoryGroupedClass</code>中。现在我们可以为每一个工厂生成 java 文件了:</p>    <pre>  <code class="language-java">public boolean process(Set<? extends TypeElement> annotations,    RoundEnvironment roundEnv) {    ...   try {    for (FactoryGroupedClasses factoryClass : factoryClasses.values()) {     factoryClass.generateCode(elementUtils, filer);    }   } catch (IOException e) {    error(null, e.getMessage());   }      return true;  }</code></pre>    <p>写 java 文件跟写其他文件完全一样。我们可以使用<code>Filer</code>提供的一个<code>Writer</code>对象来操作。我们可以用字符串拼接的方法写入我们生成的代码。幸运的是,Square公司(因为提供了许多非常优秀的开源项目二非常有名)给我们提供了<a href="/misc/goto?guid=4959676356704058713" rel="external"><code>JavaWriter</code></a>,这是一个高级的生成Java代码的库:</p>    <pre>  <code class="language-java">package com.example.apt;    import java.io.IOException;  import java.io.Writer;  import java.util.EnumSet;  import java.util.LinkedHashMap;  import java.util.Map;    import javax.annotation.processing.Filer;  import javax.lang.model.element.Modifier;  import javax.lang.model.element.PackageElement;  import javax.lang.model.element.TypeElement;  import javax.lang.model.util.Elements;  import javax.tools.JavaFileObject;    import com.squareup.javawriter.JavaWriter;    public class FactoryGroupedClasses {     /**    * Will be added to the name of the generated factory class    */   private static final String SUFFIX = "Factory";     private String qualifiedClassName;     private Map<String, FactoryAnnotatedClass> itemsMap = new LinkedHashMap<String, FactoryAnnotatedClass>();     public FactoryGroupedClasses(String qualifiedClassName) {    this.qualifiedClassName = qualifiedClassName;   }     public void add(FactoryAnnotatedClass toInsert)     throws IdAlreadyUsedException {      FactoryAnnotatedClass existing = itemsMap.get(toInsert.getId());    if (existing != null) {     throw new IdAlreadyUsedException(existing);    }      itemsMap.put(toInsert.getId(), toInsert);   }     public void generateCode(Elements elementUtils, Filer filer)     throws IOException {    TypeElement superClassName = elementUtils      .getTypeElement(qualifiedClassName);    String factoryClassName = superClassName.getSimpleName() + SUFFIX;      JavaFileObject jfo = filer      .createSourceFile(qualifiedClassName + SUFFIX);    Writer writer = jfo.openWriter();    JavaWriter jw = new JavaWriter(writer);      // Write package    PackageElement pkg = elementUtils.getPackageOf(superClassName);    if (!pkg.isUnnamed()) {     jw.emitPackage(pkg.getQualifiedName().toString());     jw.emitEmptyLine();    } else {     jw.emitPackage("");    }      jw.beginType(factoryClassName, "class", EnumSet.of(Modifier.PUBLIC));    jw.emitEmptyLine();    jw.beginMethod(qualifiedClassName, "create",      EnumSet.of(Modifier.PUBLIC), "String", "id");      jw.beginControlFlow("if (id == null)");    jw.emitStatement("throw new IllegalArgumentException(\"id is null!\")");    jw.endControlFlow();      for (FactoryAnnotatedClass item : itemsMap.values()) {     jw.beginControlFlow("if (\"%s\".equals(id))", item.getId());     jw.emitStatement("return new %s()", item.getTypeElement()       .getQualifiedName().toString());     jw.endControlFlow();     jw.emitEmptyLine();    }    jw.emitStatement("throw new IllegalArgumentException(\"Unknown id = \" + id)");    jw.endMethod();      jw.endType();      jw.close();   }  }</code></pre>    <h2>13. 处理循环</h2>    <p>注解处理器可能会有多次处理过程。官方文档解释如下:</p>    <blockquote>     <p>Annotation processing happens in a sequence of rounds. On each round, a processor may be asked to process a subset of the annotations found on the source and class files produced by a prior round. The inputs to the first round of processing are the initial inputs to a run of the tool; these initial inputs can be regarded as the output of a virtual zeroth round of processing.</p>    </blockquote>    <p>一个简单的例子:第一轮处理调用了注解处理器的<code>process()</code>方法。对应到我们工厂模式的例子:<code>FactoryProcessor</code>被初始化一次(不是每次循环都会新建处理器对象),但<code>process()</code>可以被多次调用,如果新生成了 java 文件。这听起来有点奇怪,是不?原因是,新生成的源代码文件中也可能包含有<code>@Factory</code>注解,这些文件也将会被<code>FactoryProcessor</code>处理。<br> 对于我们的<code>PizzaStore</code>来说,将会有三轮处理:</p>    <table>     <tbody>      <tr>       <th>Round</th>       <th>Input</th>       <th>Output</th>      </tr>      <tr>       <td>1</td>       <td>CalzonePizza.java <br> Tiramisu.java<br> MargheritaPizza.java<br> Meal.java<br> PizzaStore.java</td>       <td>MealFactory.java</td>      </tr>      <tr>       <td>2</td>       <td>MealFactory.java</td>       <td>— none —</td>      </tr>      <tr>       <td>3</td>       <td>— none —</td>       <td>— none —</td>      </tr>     </tbody>    </table>    <p><br> 我在这里解释处理循环还有另外一个原因。如果你仔细看我们的<code>FactoryProcessor</code>代码,你就会发现,我们把收集的数据保存到私有成员变量<code>Map<String, FactoryGroupedClasses> factoryClasses</code>。在第一轮循环中,我们检测到MagheritaPizza, CalzonePizza 和 Tiramisu 然后我们生成了MealFactory.java 文件。在第二轮循环中我们把 MealFactory.java 当作输入。由于 MealFactory.java 没有<code>@Factory</code>注解,所以没有数据被收集,我们预期不会有错误。但是我们得到了下面这个错误:<br> <code>Attempt to recreate a file for type com.hannesdorfmann.annotationprocessing101.factory.MealFactory</code><br> 这个问题在于,我们从来没有清空过<code>factoryClasses</code>。那意味着,在第二轮处理中,<code>process()</code>仍然保存着第一轮收集的数据,然后想创建跟第一轮已经创建的相同文件(MealFactory), 这就导致了这个错误。在我们的例子中,我们知道,只有第一轮我们会检测被<code>@Factory</code>注解的类,因此我们可以简单的像下面这样子修正:</p>    <pre>  <code class="language-java">public boolean process(Set<? extends TypeElement> annotations,    RoundEnvironment roundEnv) {   try {    for (FactoryGroupedClasses factoryClass : factoryClasses.values()) {     factoryClass.generateCode(elementUtils, filer);    }      // Clear to fix the problem    factoryClasses.clear();     } catch (IOException e) {    error(null, e.getMessage());   }   ...  }</code></pre>    <p>我知道还可以用其他方法来解决这个问题。比如,我们可以设置一个 boolean 标志等等。关键点在于:我们要记住,注解处理器会经过多轮循环处理(每一轮都是通过调用<code>process()</code>方法),我们不能覆盖我们已经生成的代码文件。</p>    <h2>14. 分离处理器和注解</h2>    <p>如果你有看我们<a href="/misc/goto?guid=4959626544105582548" rel="external"><code>github</code></a>上的工厂处理器代码。你就会发现,我们组织代码到两个模块中。我们之所以那样做,是因为我们想让我们工厂例子的使用者在他们在工程中只编译注解,包含处理器模块只是为了编译。这样做的原因是,在发布程序时注解及生成的代码会被打包到用户程序中,而注解处理器则不会(注解处理器对用户的程序运行是没有用的)。假如注解处理器中使用到了其他第三方库,那就会占用系统资源。如果你是一个 android 开发者,你可能会听说过 65K 方法限制(一个android 的 .dex 文件,最多只可以有 65K 个方法)。如果你在注解处理器中使用了 <code>Guava</code>,并且把注解和处理器打包在一个包中,这样的话,Android APK安装包中不只是包含<code>FactoryProcessor</code>的代码,而也包含了整个<code>Guava</code>的代码。<code>Guava</code>有大约20000个方法。所以分开注解和处理器是非常有意义的。</p>    <h2>15. 实例化生成的类</h2>    <p>你已经看到了,在这个<code>PizzaStore</code>的例子中,生成了<code>MealFactory</code>类,它和其他手写的 java 类没有任何区别。你需要手动实例化它(跟其他 java 对象一样):</p>    <pre>  <code class="language-java">public class PizzaStore {      private MealFactory factory = new MealFactory();      public Meal order(String mealName) {      return factory.create(mealName);    }      ...  }</code></pre>    <p>当然,你也可以使用反射的方法来实例化。这篇文章的主题是注解处理器,所以就不作过多的讨论了。</p>    <h2>16. 总结</h2>    <p>我希望,你现在对注解处理器已经有比较深的印象了。我必须要再次强调的是:注解处理器是一个非常强大的工具,它可以帮助减少很多无聊代码的编写。我也想提醒的是,跟我的简单工厂例子比起来,注解处理器可以做更多复杂的工作。例如,泛型的类型擦除,因为注解处理器是发生在类型擦除(type erasure)之前的。就像你所看到的,你在写注解处理的时候,有两个普遍的问题你必须要处理:1. 如果你想要在其他类中使用 ElementUtils, TypeUtils 和 Messager,你必须把它们作为参数传给它们。2. 你必须做查询Elements的操作。就像之前提到的,处理Element就和解析XML或者HTML一样。对于HTML你可以是用jQuery,如果在注解处理器中,有类似于jQuery的库那真是非常方便的。</p>    <p>最后一段是作者的提醒,原文如下:</p>    <blockquote>     <p>Please note that parts of the code of FactoryProcessor has some edges and pitfalls. These “mistakes” are placed explicit by me to struggle through them as I explain common mistakes while writing annotation processors (like “Attempt to recreate a file”). If you start writing your own annotation processor based on FactoryProcessor DON’T copy and paste this pitfalls. Instead you should avoid them from the very beginning.</p>    </blockquote>    <p>来自:http://qiushao.net/2015/07/07/Annotation-Processing-Tool%E8%AF%A6%E8%A7%A3/</p>    <p> </p>