gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 13:34:54 25 4
gpt4 key购买 nike

我有以下注释:

@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
}

我需要在我的注释处理器中获取 ownerconsumer 的值。

我试过这种方法:

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 值。

所以这就是我现在被困的地方,感谢任何帮助。谢谢!

最佳答案

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

The annotation returned by this method could contain an element whose value is of type Class. This value cannot be returned directly: information necessary to locate and load a class (such as the class loader to use) is not available, and the class might not be loadable at all. Attempting to read a Class object by invoking the relevant method on the returned annotation will result in a MirroredTypeException, from which the corresponding TypeMirror may be extracted. Similarly, attempting to read a Class[]-valued element will result in a 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 }

并返回 DataOwnerTypeMirror

关于java - Kotlin - 如何从注释处理器获取 KClass<*> 注释参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58448038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com