Actual combat and analysis of APT application scenarios in Android

First, what is APT

1.APT (Annotation Processing Tool) is a tool for processing annotations. It detects source code files to find the Annotation in it, and uses Annotation for additional processing.

The Annotation processor can generate additional source files and other files according to the Annotation in the source file when processing Annotation (the specific content of the file is determined by the Annotation processor's

The author decides), APT will also compile the generated source file and the original source file, and generate a class file together. APT mainly relies on javac in the Java compilation link, we are controlling

The processor tool will appear when you input javac on the platform. This is the entry of the APT handler. Simply put, the Processor will be initialized during the compilation phase, and then the code in the current module will be

The code is scanned once, and then the corresponding annotation is obtained, and then the process method is called, and then we do some follow-up operations according to these annotation classes, as shown in Figure 1

figure 1

2. In order to understand this process more conveniently and accurately, we need to know what the entire java compilation process looks like, as shown in Figure 2

figure 2

The picture above is a simple compilation flow chart, and compiler represents our javac (java language programming compiler). This picture should actually lack a process, in the process of source -> complier

We should add our Processor, Figure 3

Combining the two pictures is the entire java compilation process. The whole compilation process is source (source code) -> processor (processor) -> generate (file generation) -> javacompiler -> .

class file -> .dex (only for Android)

3. Core classes and interfaces in APT 4

Figure 4

Core classes and interfaces Figure 5

Figure 5

4. Explanation of the core method

ProcessingEnvironment

Filer 就是文件流输出路径,当我们用AbstractProcess生成一个java类的时候,我们需要保存在Filer指定的目录下。

Messager 输出日志工具,需要输出一些日志相关的时候我们就要使用这个了。

Elements 获取元素信息的工具,比如说一些类信息继承关系等。

Types 类型相关的工具类,processor java代码不同的是,当process执行的时候,class的由于类并没有被传递出来,所以大部分都行都是用element来代替了,

所以很多类型比较等等的就会转化成type相关的进行比较了。

类型相关的都被转化成了一个叫TypeMirror,其getKind方法返回类型信息,其中包含了基础类型以及引用类型。

process

@AutoService(Processor.class)

public class MyProcess extends AbstractProcessor {

private Elements elementUtils;

private Filer filer;

Messager messager;

private Name simpleName;

@Override

public synchronized void init(ProcessingEnvironment processingEnvironment) {

super.init(processingEnvironment);

elementUtils = processingEnvironment.getElementUtils();

filer = proce

Guess you like

Origin blog.csdn.net/qq_18757557/article/details/128551941