添加注解处理器

本页面包含有关如何将注解处理器添加和配置为项目依赖项的详细指南。如需详细了解注解处理器,请参阅配置依赖项中的条目。

如果将注释处理器添加到编译类路径,您将看到一条与以下内容类似的错误消息:

Error: Annotation processors must be explicitly declared now.

如需解决此错误,请使用 annotationProcessor 配置依赖项,将注解处理器添加到您的项目,如下所示:

KotlinGroovy
dependencies {
   
// Adds libraries defining annotations to only the compile classpath.
    compileOnly
("com.google.dagger:dagger:version-number")
   
// Adds the annotation processor dependency to the annotation processor classpath.
    annotationProcessor
("com.google.dagger:dagger-compiler:version-number")
}
dependencies {
   
// Adds libraries defining annotations to only the compile classpath.
    compileOnly
'com.google.dagger:dagger:version-number'
   
// Adds the annotation processor dependency to the annotation processor classpath.
    annotationProcessor
'com.google.dagger:dagger-compiler:version-number'
}

注意:Android Plugin for Gradle 3.0.0 及更高版本不再支持 android-apt 插件

向注解处理器传递参数

如果需要向注解处理器传递参数,您可以使用模块 build 配置中的 AnnotationProcessorOptions 代码块执行此操作。例如,如果要以键值对形式传递基元数据类型,您可以使用 argument 属性,如下所示:

KotlinGroovy
android {
   
...
    defaultConfig
{
       
...
        javaCompileOptions
{
            annotationProcessorOptions
{
                arguments
+= mapOf("key1" to "value1",
                                   
"key2" to "value2")
           
}
       
}
   
}
}
android {
   
...
    defaultConfig
{
       
...
        javaCompileOptions
{
            annotationProcessorOptions
{
                argument
'key1', 'value1'
                argument
'key2', 'value2'
           
}
       
}
   
}
}

不过,在使用 Android Gradle 插件 3.2.0 及更高版本时,您需要使用 Gradle 的 CommandLineArgumentProvider 接口传递表示文件或目录的处理器参数。

使用 CommandLineArgumentProvider 可让您或注解处理器作者将增量 build 属性类型注解应用于每个参数,从而提高增量 build 和缓存整洁 build 的正确性和性能。

例如,下面的类实现了 CommandLineArgumentProvider 并注解了处理器的每个参数。

KotlinGroovy
class MyArgsProvider(
   
// Annotates each directory as either an input or output for the
   
// annotation processor.
   
@get:InputFiles
   
// Using this annotation helps Gradle determine which part of the file path
   
// should be considered during up-to-date checks.
   
@get:PathSensitive(PathSensitivity.RELATIVE)
   
val inputDir: FileCollection,

   
@get:OutputDirectory
   
val outputDir: File
) : CommandLineArgumentProvider {
   
// Specifies each directory as a command line argument for the processor.
   
// The Android plugin uses this method to pass the arguments to the
   
// annotation processor.

   
override fun asArguments(): Iterable<String> {
       
// Use the form '-Akey[=value]' to pass your options to the Java compiler.
       
return listOf("-AinputDir=${inputDir.singleFile.absolutePath}",
                     
"-AoutputDir=${outputDir.absolutePath}")
   
}
}

android
{...}
class MyArgsProvider implements CommandLineArgumentProvider {

   
// Annotates each directory as either an input or output for the
   
// annotation processor.
   
@InputFiles
   
// Using this annotation helps Gradle determine which part of the file path
   
// should be considered during up-to-date checks.
   
@PathSensitive(PathSensitivity.RELATIVE)
   
FileCollection inputDir

   
@OutputDirectory
   
File outputDir

   
// The class constructor sets the paths for the input and output directories.
   
MyArgsProvider(FileCollection input, File output) {
        inputDir
= input
        outputDir
= output
   
}

   
// Specifies each directory as a command line argument for the processor.
   
// The Android plugin uses this method to pass the arguments to the
   
// annotation processor.
   
@Override
   
Iterable<String> asArguments() {
       
// Use the form '-Akey[=value]' to pass your options to the Java compiler.
       
["-AinputDir=${inputDir.singleFile.absolutePath}",
         
"-AoutputDir=${outputDir.absolutePath}"]
   
}
}

android
{...}

定义一个实现 CommandLineArgumentProvider 的类后,您需要创建一个实例,并使用 annotationProcessorOptions.compilerArgumentProvider 方法将该实例传递给 Android 插件,如下所示:

KotlinGroovy
// This is in your module's build.gradle file.
android
{
    defaultConfig
{
        javaCompileOptions
{
            annotationProcessorOptions
{
               
// Creates a new MyArgsProvider object, specifies the input and
               
// output paths for the constructor, and passes the object
               
// to the Android plugin.
                compilerArgumentProvider
(MyArgsProvider(files("input/path"),
                                                          file
("output/path")))
           
}
       
}
   
}
}
// This is in your module's build.gradle file.
android
{
    defaultConfig
{
        javaCompileOptions
{
            annotationProcessorOptions
{
               
// Creates a new MyArgsProvider object, specifies the input and
               
// output paths for the constructor, and passes the object
               
// to the Android plugin.
                compilerArgumentProvider
new MyArgsProvider(files("input/path"),
                                         
new File("output/path"))
           
}
       
}
   
}
}

如需详细了解实现 CommandLineArgumentProvider 如何帮助提高构建性能,请阅读缓存 Java 项目

停用注解处理器错误检查

如果编译类路径中的依赖项包含您不需要的注解处理器,您可以通过将以下代码添加到 build.gradle.kts 文件来停用错误检查。请注意,您添加到编译类路径中的注释处理器仍不会被添加到处理器类路径中。

KotlinGroovy
android {
   
...
    defaultConfig
{
       
...
        javaCompileOptions
{
            annotationProcessorOptions
{
                argument
("includeCompileClasspath", "false")
           
}
       
}
   
}
}
android {
   
...
    defaultConfig
{
       
...
        javaCompileOptions
{
            annotationProcessorOptions
{
                includeCompileClasspath
false
           
}
       
}
   
}
}

如果您使用 Kotlin 和 kapt

KotlinGroovy
android {
   
...
    defaultConfig
{
       
...
        kapt
{
            includeCompileClasspath
= false
       
}
   
}
}
android {
   
...
    defaultConfig
{
       
...
        kapt
{
            includeCompileClasspath
false
       
}
   
}
}

如果在将项目的注释处理器迁移到处理器类路径后遇到问题,您可以通过将 includeCompileClasspath 设为 true,允许编译类路径中包含注释处理器。不过,不建议将此属性设为 true,在 Android 插件的未来更新中将会移除用来执行此操作的选项。