Annotation Process

主要是生成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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容