preface

After reading the source code of the routing framework of the company the day before yesterday, I decided to use Apt instead of reflection to do it, because the famous ButterKnife/Dragger is implemented with Apt, so I want to see what is interesting.

In this article, we use APT to realize button click control, which is also a paving of the routing framework. The manual code has been uploaded to Github.

Github address of the project

https://github.com/maokai1229/FastClick
Copy the code

A link to the

An Example of Android annotations modeled after ButterKnife

Android compile time annotations – improved

Android compile time annotation APT combat

Details the use of compile-time annotations

APT principle

APT uses Javax’s annotation library to scan code at compile time, pass elements of custom annotations into the annotation processor’s process() method, and generate the desired code. Such as generating Java files.

Generating code is simple: concatenate strings with a StringBuilder and generate Java files through utility classes

Construction Process analysis

  1. Build project, partition code generation module /Apt call module
  2. Inherit AbstarctProcessor and override the process method
  3. Build code generation module jar package
  4. The Apt call module imports the JAR package
  5. The Apt call module injects the generated code into source code

A couple of questions about Apt

  • Why can’t the modifiers for the ButterKnife annotation method be private?

I have encountered this problem before, and it was solved after I came into contact with Apt. This is because Apt technology will automatically generate code in the same package and inject it into the source code when it is used. In the same package, private decorated methods are not visible to Apt.

  • When does Apt generate code intervene?

BufferKnife and the FastClick that we are going to handlift today are both initialized with the Activity/View. After the setContentView method is executed, we will use fastclick.init (). Method in which Apt generated methods are injected into source code.

  • Why create a separate Java library module?

This is because apt-related code is stored in a library called Javax, and our Android library cannot use the Javax package unless we download a JAR file from the Internet as our library file. So we need to create a separate module, just outside of the module, which is only responsible for generating code using Apt.

  • What is the difference between Apt and reflection?

Apt is based on compile-time annotations. Previously, we used reflection annotations based on runtime annotations, but this way will do time-consuming traversal operations at runtime, so performance problems have been criticized. Apt also requires reflection to create objects, but does not involve time-consuming operations. So it has its advantages in terms of performance.