Anmerkungsprozessoren hinzufügen

Diese Seite enthält eine detaillierte Anleitung zum Hinzufügen und Konfigurieren von Annotationsprozessoren als Projektabhängigkeiten. Weitere Informationen zu Annotationsprozessoren finden Sie im Eintrag Abhängigkeiten konfigurieren.

Wenn Sie Ihrem kompilierten Klassenpfad Annotationsprozessoren hinzufügen, erhalten Sie eine Fehlermeldung ähnlich der folgenden:

Error: Annotation processors must be explicitly declared now.

Fügen Sie Ihrem Projekt Annotationsprozessoren hinzu, um diesen Fehler zu beheben. Konfigurieren Sie dazu die Abhängigkeit mit annotationProcessor wie unten gezeigt:

Kotlin

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")
}

Groovig

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'
}

Hinweis:Das Android-Plug-in für Gradle 3.0.0 und höher unterstützt das android-apt-Plug-in nicht mehr.

Argumente an Annotationsprozessoren übergeben

Wenn Sie Argumente an einen Annotationsprozessor übergeben müssen, können Sie dies mithilfe des Blocks AnnotationProcessorOptions in der Build-Konfiguration des Moduls tun. Wenn Sie beispielsweise primitive Datentypen als Schlüssel/Wert-Paare übergeben möchten, können Sie das Attribut argument so verwenden:

Kotlin

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

Groovig

android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                argument 'key1', 'value1'
                argument 'key2', 'value2'
            }
        }
    }
}

Wenn Sie jedoch das Android-Gradle-Plug-in 3.2.0 und höher verwenden, müssen Sie Prozessorargumente übergeben, die Dateien oder Verzeichnisse mithilfe der Gradle-Schnittstelle CommandLineArgumentProvider darstellen.

Mit CommandLineArgumentProvider können Sie oder der Autor des Annotationsprozessors die Korrektheit und Leistung von inkrementellen und im Cache gespeicherten sauberen Builds verbessern, indem Sie inkrementelle Build-Attribut-Annotationen auf jedes Argument anwenden.

Die folgende Klasse implementiert beispielsweise CommandLineArgumentProvider und annotiert jedes Argument für den Prozessor.

Kotlin

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 {...}

Groovig

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 {...}

Nachdem Sie eine Klasse definiert haben, die CommandLineArgumentProvider implementiert, müssen Sie eine Instanz erstellen und sie mithilfe der Methode annotationProcessorOptions.compilerArgumentProvider wie unten gezeigt an das Android-Plug-in übergeben.

Kotlin

// 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")))
            }
        }
    }
}

Groovig

// 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"))
            }
        }
    }
}

Weitere Informationen dazu, wie die Implementierung von CommandLineArgumentProvider zur Verbesserung der Build-Leistung beiträgt, findest du unter Java-Projekte im Cache speichern.

Fehlerprüfung durch den Annotationsprozessor deaktivieren

Wenn Sie Abhängigkeiten vom Kompilierungsklassenpfad haben, der Annotationsprozessoren enthält, die Sie nicht benötigen, können Sie die Fehlerprüfung deaktivieren, indem Sie der Datei build.gradle.kts Folgendes hinzufügen: Beachten Sie, dass die Annotationsprozessoren, die Sie dem Compile-Klassenpfad hinzufügen, dem Prozessorklassenpfad weiterhin nicht hinzugefügt werden.

Kotlin

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

Groovig

android {
    ...
    defaultConfig {
        ...
        javaCompileOptions {
            annotationProcessorOptions {
                includeCompileClasspath false
            }
        }
    }
}

Wenn Sie Kotlin und kapt verwenden:

Kotlin

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

Groovig

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

Wenn nach der Migration der Annotationsprozessoren Ihres Projekts zum Prozessorklassenpfad Probleme auftreten, können Sie Annotationsprozessoren im Kompilierungsklassenpfad zulassen. Dazu setzen Sie includeCompileClasspath auf true. Es wird jedoch nicht empfohlen, dieses Attribut auf true festzulegen. Diese Option wird in einem zukünftigen Update des Android-Plug-ins entfernt.