На этой странице вы найдете подробные инструкции по добавлению и настройке инструментов обработки аннотаций в качестве зависимостей проекта. Подробнее о настройке зависимостей…
Если вы добавите инструменты обработки аннотаций в путь к классам компиляции, то увидите сообщение об ошибке, похожее на следующее:
Error: Annotation processors must be explicitly declared now.
Чтобы устранить эту ошибку, добавьте в проект инструменты обработки аннотаций, настроив зависимость с помощью annotationProcessor, как показано в примере ниже.
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") }
Яркий
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' }
Передача аргументов инструментам обработки аннотаций
Если вам нужно передать аргументы инструменту обработки аннотаций, используйте блок AnnotationProcessorOptions в конфигурации сборки модуля. Например, если вы хотите передавать примитивные типы данных в виде пар "ключ-значение", используйте свойство argument, как показано в примере ниже.
Kotlin
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, вы или автор инструмента обработки аннотаций можете повысить точность и эффективность инкрементных и кешированных чистых сборок, применив аннотации типа свойства инкрементной сборки к каждому аргументу.
Например, класс в примере ниже реализует CommandLineArgumentProvider и аннотирует каждый аргумент для обработчика.
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 {...}
Яркий
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, вам нужно создать экземпляр и передать его плагину Android с помощью метода annotationProcessorOptions.compilerArgumentProvider, как показано в примере ниже.
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"))) } } } }
Яркий
// 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 следующий код: Обратите внимание, что инструменты обработки аннотаций, добавленные в путь к классам компиляции, не добавляются в путь к классам процессора.
Kotlin
android { ... defaultConfig { ... javaCompileOptions { annotationProcessorOptions { argument("includeCompileClasspath", "false") } } } }
Яркий
android { ... defaultConfig { ... javaCompileOptions { annotationProcessorOptions { includeCompileClasspath false } } } }
Если вы используете Kotlin и kapt:
Kotlin
android { ... defaultConfig { ... kapt { includeCompileClasspath = false } } }
Яркий
android { ... defaultConfig { ... kapt { includeCompileClasspath false } } }
Если после переноса инструментов обработки аннотаций в путь к классам процессора у вас возникли проблемы, вы можете разрешить инструменты обработки аннотаций в пути к классам компиляции, задав для includeCompileClasspath значение true. Однако задавать для этого свойства значение true не рекомендуется, и в будущем обновлении плагина Android такая возможность будет удалена.