Annotation Process

2017-04-28  本文已影响22人  yangweigbh

主要是生成jar包,jar包格式:

MyProcessor.jar
    - com
        - example
            - MyProcessor.class

    - META-INF
        - services
            - javax.annotation.processing.Processor

处理Annotation放在自定义的Processor中

@SupportedSourceVersion(SourceVersion.latestSupported())
@SupportedAnnotationTypes({
   // Set of full qullified annotation type names
 })
public class MyProcessor extends AbstractProcessor {

    @Override
    public synchronized void init(ProcessingEnvironment env){ }

    @Override
    public boolean process(Set<? extends TypeElement> annoations, RoundEnvironment env) { }
}

Java源代码被分解各个元素(Element)

package com.example;    // PackageElement

public class Foo {      // TypeElement

    private int a;      // VariableElement
    private Foo other;  // VariableElement

    public Foo () {}    // ExecuteableElement

    public void setA (  // ExecuteableElement
                     int newA   // TypeElement
                     ) {}
}
annotation.png

TypeElement表示的是类或者接口定义,只能得到类的名字,但是没有父类信息,类信息保存在TypeMirror中,TypeElement的asType()返回DeclaredType

Paste_Image.png

Annotation Processor发生在编译源文件之前,如果源文件没有编译成class文件,访问类对应的class则会抛出MirroredTypeException,MirrorTypeException中可以得到DeclaredType。

通过Filer创建Java文件。可以通过JavaPoet简化Java文件的生成

Annotation Processor分为很多round,初次round的输入是原始文件,输出是生成的文件。下一round的输入时生成的文件,如果没有生成的文件,则最后会再走一轮

Paste_Image.png
上一篇 下一篇

猜你喜欢

热点阅读