我有一个自定义注释处理器,大致执行以下操作:
- 生成注释类型(使用此类型的类被推迟到后面的轮次)
- 在后面的一轮中,使用这种类型处理类并为它们生成更多文件
到目前为止,这在 Java 中运行良好。但最近,我将一些类从 Java 转换为 Kotlin。设置仍然相同。
但是当我使用生成的注释类型将类转换为 Kotlin 时,会弹出以下错误:
错误:不兼容的类型:NonExistentClass 无法转换为 Annotation
@error.NonExistentClass()
值得注意的是,只有当文件位于 Kotlin 中时才会发生这种情况 - 其他(Java)文件也使用相同的注释,并且当我从 Kotlin 文件中删除注释时它们不会产生错误。
经过一番谷歌搜索后,我发现推荐的解决方案是添加一个选项 https://kotlinlang.org/docs/reference/kapt.html#non-existent-type-correction to the build.gradle
:
kapt {
correctErrorTypes = true
}
然而,使用这个并没有解决问题。我查看了生成的存根文件,很明显kapt
不断投入error.NonExistentClass
尽管设置在那里:
package my.pckg;
import my.pckg.GeneratedAnnotation;
@kotlin.Metadata(...)
public final class MyClass {
private int myAnnotatedField;
@error.NonExistentClass()
public static void myAnnotatedField$annotations() {
}
public final int getMyAnnotatedField() {
return 0;
}
public final void setMyAnnotatedField(int p0) {
}
//...
}
我认为值得注意的是:
- 存根保留了生成注释的正确导入
-
kapt
将注释移至静态方法,而原始生成的注释仅支持字段
MyClass
看起来像这样:
package my.pckg
import my.pckg.GeneratedAnnotation
class MyClass {
@GeneratedAnnotation
var myAnnotatedField: Int = 0
//...
}
这是build.gradle
:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
//...
kotlinOptions {
jvmTarget = '1.8'
}
}
kapt {
correctErrorTypes = true
}
dependencies {
kapt 'custom.annotation.processor'
implementation "androidx.core:core-ktx:+"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.41"
//...
}
There 曾经是其他的 https://stackoverflow.com/questions/56863896/nonexistentclass-cannot-be-converted-to-annotation-appkaptdebugandroidtestkot 人与 https://stackoverflow.com/questions/54919848/error-incompatible-types-nonexistentclass-cannot-be-converted-to-annotation-e 这个问题 https://stackoverflow.com/questions/54564247/nonexistentclass-cannot-be-converted-to-annotation on SO https://stackoverflow.com/questions/50629304/kapt-nonexistentclass-exception-in-a-retrofit-interface-after-migrating-to-andro,但那里建议的解决方案都没有为我解决这个问题。
Edit:我做了更多测试,发现生成的类型是only取而代之error.NonExistentClass
当类型用作注释时(作为对象类型甚至泛型参数,它可以正常工作)。在这一点上,我相信这可能只是一个kapt
bug https://youtrack.jetbrains.net/issue/KT-32596.