问题描述
假设我的注释处理器的处理功能如下所示
override fun process(
annotations: MutableSet<out TypeElement>,roundEnv: RoundEnvironment
): Boolean {
try {
roundEnv.getElementsAnnotatedWith(CustomAnnotation::class.java)
.mapNotNull {
if (it.kind != ElementKind.INTERFACE) {
printError(
"Only interfaces can be annotated with " +
MapperConfig::class.java.simpleName
)
null
} else {
it as TypeElement
}
}.forEach {
processMapperConfigInterface(it,roundEnv)
}
} catch (ex: Exception) {
messager.printError(ex.message!!)
}
return true
}
roundEnv.getElementsAnnotatedWith
返回了没有任何Kotlin类型信息的Java元素,我该如何使用注释处理来获取正确的Kotlin类型信息?
解决方法
我遇到了同样的问题,我唯一能想到的解决方案是使用kotlinpoet-metadata API解析元素的元数据。
重要说明: kotlinpoet-metadata
尚处于生产初期,它本身基于实验性kotlinx-metadata
库,因此将来可能会中断。但是,当前在Moshi Kotlin code generator的稳定版本中使用它。
首先,请确保已在build.gradle中的依赖项中添加了以下内容:
dependencies {
implementation 'com.squareup:kotlinpoet:1.7.1'
implementation 'com.squareup:kotlinpoet-metadata:1.7.1'`
}
1.7.1是今天的最新KotlinPoet版本。
您可以通过KmClass
获取Kotlin类型信息,该信息由元素的元数据构造而成。这是一个使用KmClass的示例,这是您需要在代码中进行更改的地方:
override fun process(
annotations: MutableSet<out TypeElement>,roundEnv: RoundEnvironment
): Boolean {
try {
roundEnv.getElementsAnnotatedWith(CustomAnnotation::class.java)
.mapNotNull {
if (it.kind != ElementKind.INTERFACE) {
printError(
"Only interfaces can be annotated with " +
MapperConfig::class.java.simpleName
)
null
} else {
it as TypeElement
}
}.forEach {
val typeMetadata = it.getAnnotation(Metadata::class.java) ?: return@forEach
var kmClass = typeMetadata.toImmutableKmClass()
// HERE: kmClass should contain all the Kotlin type information.
}
} catch (ex: Exception) {
messager.printError(ex.message!!)
}
return true
}