Joke Collection Website - Mood Talk - How to use a custom annotation processor in android studio

How to use a custom annotation processor in android studio

The method of using custom annotation processor in android studio is realized by using the third-party gradle plug-in android-apt.

Note: Android Studio does not initially support annotation processors. This plug-in can automatically help the programmer to create a directory for the generated code, so that the generated code can be compiled into APK, or the finally compiled APK can not contain the code of the annotation processor itself, because this part of the code only needs to be generated at compile time, but not at run time.

1. Using this plug-in is very simple. First, add dependencies in the build.gradle file at the top of the project, as shown below:

Build script {

Repository {

jcenter()

}

Dependency {

Classpath' com.android.tools.build: gradle:1.5.0'

Classpath' com.neenbedankt.gradle.plugins: Android-apt:1.8'

}

}

2. Then add the reference of the plug-in and which libraries need to be relied on in the build.gradle of the app, as follows:

Application plug-in: "com.android.application"

Application plug-in: "com.neenbedankt.android-apt"

...

Dependency {

Compile the file tree (directory:' libs', including: ['*. jar'])

test compile ' JUnit:JUnit:4. 12 '

Compile "com.android.support: appcompat-V7: 22.2.1"

Compile "la.dahuo:command: 1.0.0"

apt ' la . dahuo:command-codegen: 1 . 0 . 0 '

}

Pay attention to apt' la. Huo Da: The above command-codegen: 1. 0. 0' refers to the annotation processor's library, and the code of this library will not enter the compiled APK eventually.

3. Use comments to generate code, and the library la.dahuo:command appears on it. La.dahuo:command-codegen is an annotation library that I wrote according to the command design pattern, which is used for us to generate code conveniently. View usage:

Define command

@CommandDef("commandName ")

Common class MyCommand extension command {

@Param

String paramStr

@Param("paramIntName ")

int paramInt

@ Overlay

public void execute() {

//Do something with parameters

}

}