美文网首页
Annotation Process

Annotation Process

作者: yangweigbh | 来源:发表于2017-04-28 01:51 被阅读22次

    主要是生成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

    相关文章

      网友评论

          本文标题:Annotation Process

          本文链接:https://www.haomeiwen.com/subject/kuinzttx.html