Dodaj procesory adnotacji

Ta strona zawiera szczegółowe wskazówki na temat dodawania i konfigurowania podmiotów przetwarzających adnotacje jako zależności projektu. Więcej informacji o procesorach adnotacji znajdziesz w artykule Konfigurowanie zależności.

Jeśli dodasz procesory adnotacji do ścieżki klasy kompilacji, zobaczysz komunikat o błędzie podobny do tego:

Error: Annotation processors must be explicitly declared now.

Aby naprawić ten błąd, dodaj procesory adnotacji do swojego projektu, konfigurując zależność za pomocą annotationProcessor, jak pokazano poniżej:

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

Odlotowy

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

Uwaga: wtyczka na Androida do obsługi Gradle w wersji 3.0.0 lub nowszej nie obsługuje już wtyczki android-apt.

Przekazywanie argumentów do procesorów adnotacji

Jeśli musisz przekazywać argumenty do procesora adnotacji, możesz to zrobić za pomocą bloku AnnotationProcessorOptions w konfiguracji kompilacji modułu. Jeśli np. chcesz przekazywać podstawowe typy danych w postaci par klucz-wartość, możesz użyć właściwości argument w ten sposób:

Kotlin

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

Odlotowy

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

Jeśli jednak używasz wtyczki Androida do obsługi Gradle w wersji 3.2.0 lub nowszej, musisz przekazywać argumenty procesora, które reprezentują pliki lub katalogi za pomocą interfejsu CommandLineArgumentProvider Gradle.

Korzystanie z metody CommandLineArgumentProvider umożliwia Tobie lub autorowi procesora adnotacji polepszanie poprawności i wydajności oczyszczonych kompilacji w pamięci podręcznej przez zastosowanie do każdego argumentu adnotacji typu przyrostowej kompilacji.

Na przykład klasa poniżej implementuje funkcję CommandLineArgumentProvider i dodaje adnotacje do każdego argumentu procesora.

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

Odlotowy

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

Po zdefiniowaniu klasy z implementacją CommandLineArgumentProvider musisz utworzyć instancję i przekazać ją do wtyczki na Androida za pomocą metody annotationProcessorOptions.compilerArgumentProvider, jak pokazano poniżej.

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

Odlotowy

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

Więcej informacji o tym, jak wdrożenie CommandLineArgumentProvider pomaga poprawić wydajność kompilacji, znajdziesz w artykule o buforowaniu projektów Java.

Wyłącz sprawdzanie błędów procesora adnotacji

Jeśli masz zależności od ścieżki klasy kompilacji obejmujące procesory adnotacji, których nie potrzebujesz, możesz wyłączyć sprawdzanie błędów, dodając ten kod do pliku build.gradle.kts. Pamiętaj, że procesory adnotacji dodane do ścieżki klasy kompilowania nadal nie są dodawane do ścieżki klasy procesora.

Kotlin

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

Odlotowy

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

Jeśli używasz Kotlin i kapt:

Kotlin

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

Odlotowy

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

Jeśli po przeniesieniu procesorów adnotacji z projektu do ścieżki klasy procesora wystąpią problemy, możesz zezwolić na procesory adnotacji na ścieżce klasy kompilacji, ustawiając w includeCompileClasspath wartość true. Nie zalecamy jednak ustawienia tej właściwości na true. Zostanie ona usunięta w kolejnej aktualizacji wtyczki na Androida.