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