Kotlin - 如何从注释处理器获取 KClass<*> 注释参数

问题描述 投票:0回答:2

我有以下注释:

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.SOURCE)
@MustBeDocumented
annotation class Model(
    val owner: KClass<*>,
    val consumer: KClass<*>
)

@Model(DataOwner::class, DataConsumer::class)
interface Student {
    val name: String
    val group: Group
}

我需要在注释处理器中获取

owner
consumer
的值。

我尝试过这种方法:

private inline fun <reified T> findAnnotationValue(
    element: Element,
    annotationClass: KClass<*>,
    valueName: String
): T? {
    return element.annotationMirrors.map {
        it to it.annotationType.asElement() as TypeElement
    }.firstOrNull { (_, element) ->
        element.qualifiedName.contentEquals(annotationClass.qualifiedName)
    }?.let { (mirror, _) ->
        extractValue(mirror, valueName)
    }
}

private inline fun <reified T> extractValue(
    annotationMirror: AnnotationMirror,
    valueName: String
): T? {
    return annotationMirror.elementValues.toList()
        .firstOrNull { (key, _) ->
            key.simpleName.contentEquals(valueName)
        }?.let { (_, value) ->
            value.value as T
        }
}


val ownerClass: KClass<*> = findAnnotationValue(
    element,
    Model::class,
    "owner"
)

但是它给了我这个错误:

e: [kapt] An exception occurred: java.lang.ClassCastException: com.sun.tools.javac.code.Type$ClassType cannot be cast to kotlin.reflect.KClass

我也尝试过这个:

val ownerClass: KClass<*> = element.getAnnotation(Model::class.java).owner

但是它给了我这个错误:

e: [kapt] An exception occurred: javax.lang.model.type.MirroredTypeException: Attempt to access Class object for TypeMirror inc.ahmedmourad.systems.tutors.domain.model.DataOwner

inc.ahmedmourad.systems.tutors.domain.model.DataOwner
是传递给注释的
owner
值。

所以这就是我现在陷入困境的地方,非常感谢任何帮助。 谢谢!

java kotlin annotations
2个回答
3
投票

让我们从第二种方法不起作用的原因开始:

此方法返回的注释可以包含 其值为 Class 类型的元素。该值无法直接返回:定位和加载类所需的信息(例如要使用的类加载器)不可用,并且该类可能根本无法加载。 尝试通过调用相关方法来读取 Class 对象对返回的注释进行操作将导致 MirroredTypeException,从中可以提取相应的 TypeMirror。同样,尝试读取 Class[] 值元素将导致 MirroredTypesException。

这显然也适用于

KClass

因此,对于注释中的类,您只能获得

TypeMirror
(在本例中由
Type.ClassType
实现,但这是您不应该依赖的内部细节)而不是
KClass
。通过第一种方法或

inline fun <reified T : Annotation> Element.getAnnotationClassValue(f: T.() -> KClass<*>) = try { 
    getAnnotation(T::class.java).f() 
    throw Exception("Expected to get a MirroredTypeException")
} catch (e: MirroredTypeException) {
    e.typeMirror
}

可以用作

element.getAnnotationClassValue<Model> { owner }

并返回

TypeMirror
DataOwner


2
投票

如果您使用 KSP,那么解决方案可能如下所示:

使用实验性 API 并假设您在注释中引用的 KClass 可用:

resolver.getSymbolsWithAnnotation("com.example.Model")
    .map {
        val consumerType = try {
            it.getAnnotationsByType(Model::class).first().consumer
            null
        } catch (e: KSTypeNotPresentException) {
            e.ksType
        }
        val consumerDeclaration = consumerType!!.declaration as KSClassDeclaration // etc
    }

如果你做不到这一点,那么维护注释的 KSP 视图会更灵活:

resolver.getSymbolsWithAnnotation("com.example.Model")
    .map { ksAnnotated ->
        val args = ksAnnotated.annotations.single {
            it.shortName.asString() == "Model" && it.annotationType.resolve().declaration.qualifiedName?.asString() == "com.example.Model"
        }.arguments

        val consumerType = args.first { it.name?.asString() == "owner" }.value as KSType
        val consumerDeclaration = consumerType.declaration as KSClassDeclaration // etc 
    }
© www.soinside.com 2019 - 2024. All rights reserved.