源码级注解处理

Wu Jun 2020-01-02 03:43:49
Categories: > > Tags:

1 注解处理

编译器会定位源文件中的注解。每个注解处理器会依次执行。如果某个注解处理器产生了新的源文件,则重复处理。没有新文件产生后,就编译所有源文件。

注解处理器通常扩展 AbstractProcessor 类实现 Processor 接口。

@SupportedAnnotationTypes("com.xxx*")
@SupportedSourceVersion(SourveVersion.RELEASE_8)
public class ToStringAnnotationProcessor extends AbstractProcessor{
    public boolean process(Set<? extends TypeElement> annotations, RoundEnviroment currentRound){
        ...
    }
}

每轮处理 process 都会被调用一次

2 语言模型 API

编译器会生成一棵树,其节点是实现了 javax.lang.model.element.Element 接口,以及其 TypeElement、VariableElement、ExecutableElement 等子接口的类的实例。这些节点可类比于编译时的 Class、Field/Parament 和 Method/Constructor 反射类。

getElementsAnnotatedWith()
getAnnotation()
getAnnotationsByType()
getEnclosedElements()

3 使用注解生成源码

TODO