我正在尝试开发Kotlin AnnotationProcessor库,但我不知道为什么会出现此错误:
我知道,如前所述,我可以使用includeCompileClasspath = true
,我尝试了一下,效果很好。但是如前所述,它已被弃用,很快就被删除了,根据android doc,它有望用于您不使用的库。
因此,我正在寻找更清洁的解决方案。
应用模块
你好
@HelloGenerated
class Hello(){
override fun showLog() {
Log.i(Hello::class.simpleName, "${Gahfy_Hello().getName()}")
}
}
Build.gradle
依存关系{
kapt project(“:compiler”)
compileOnly project(“:compiler”)
实现“org.jetbrains.kotlin:kotlin-reflect:$ kotlin_version”
}
编译模块
HelloGenerated.kt
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
annotation class HelloGenerated
我也尝试了没有目标和保留,并且有同样的问题
HelloGenerator.kt
@SupportedAnnotationTypes("net.gahfy.HelloGenerated")
class HelloGeneratedInjectorProcessor: AbstractProcessor() {
override fun getSupportedAnnotationTypes(): MutableSet<String> {
return mutableSetOf(HelloGenerated::class.java.name)
}
override fun getSupportedSourceVersion(): SourceVersion {
return SourceVersion.latest()
}
override fun process(annotations: MutableSet<out TypeElement>, roundEnv: RoundEnvironment): Boolean {
val annotation = annotations.firstOrNull { it.toString() == "net.gahfy.HelloGenerated" } ?: return false
for (element in roundEnv.getElementsAnnotatedWith(annotation)) {
val className = element.simpleName.toString()
val `package` = processingEnv.elementUtils.getPackageOf(element).toString()
generateClass(className, `package`)
}
return true
}
private fun generateClass(className: String, `package`: String) {
val kotlinGeneratedPath = (processingEnv.options["kapt.kotlin.generated"] as String).replace("kaptKotlin", "kapt")
val kaptKotlinGenerated = File(kotlinGeneratedPath)
val source = "package $`package`\n\nclass Lachazette_$className(){fun getName():String{return \"World\"}}"
val relativePath = `package`.replace('.', File.separatorChar)
val folder = File(kaptKotlinGenerated, relativePath).apply { if(!exists()){mkdirs()} }
File(folder, "Lachazette_$className.kt").writeText(source)
}
companion object {
const val KAPT_KOTLIN_GENERATED_OPTION_NAME = "kapt.kotlin.generated"
}
}
build.gradle
apply plugin: 'java-library'
apply plugin: 'kotlin'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}
sourceCompatibility = "1.7"
targetCompatibility = "1.7"
资源/META-INF/services/javax.annotation.processing.Processor
net.gahfy.HelloGenerator
我现在正在寻找一种比
includeCompileClasspath = true
更干净的解决方案。一些信息:
includeCompileClasspath = true
非常感谢你
最佳答案
不知道这是否与您的问题100%相关,但是将auto-value移至kapt
后出现了相同的错误。我通过将自动值依赖项声明为kapt
和 annotationProcessor
来解决了这一问题。
因此,在您的情况下:
dependencies{
kapt project(":compiler")
annotationProcessor project(":compiler")
compileOnly project(":compiler")
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
}