【发布时间】:2020-02-24 10:47:17
【问题描述】:
我如何确定哪种类型具有通用模板参数?
package tutorial.test.reflection
import kotlin.reflect.KClass
import kotlin.reflect.KType
interface ModelElement
interface Parentable<T : ModelElement>
interface Parent : ModelElement
interface Interface1<PARENT_TEMPLATE : ModelElement> : Parentable<PARENT_TEMPLATE>
interface Interface2 : Interface1<Parent>
// Returns just all classifiers in the inheritance hierachy
fun getAllSupertypes(cls: KClass<*>): List<KType> = cls.supertypes.let {
val types = it.toMutableList()
cls.supertypes.forEach { types.addAll(getAllSupertypes(it.classifier as KClass<*>)) }
return types.filter { it.classifier != Any::class }
}
fun main(args: Array<String>) {
val t = getAllSupertypes(Interface2::class)
t.forEach {
println(it)
if(it.classifier == Parentable::class) {
it.arguments.forEach {
println("\t-> ${it.type} ${(it.type?.classifier == Parent::class)}")
// The template parameter must be "tutorial.test.reflection.Parent" but is PARENT_TEMPLATE
}
}
}
}
输出
tutorial.test.reflection.Interface1
tutorial.test.reflection.Parentable -> PARENT_TEMPLATE 错误
(it.type?.classifier == Parent::class) 应该结果为真。如何从继承层次结构中将通用模板参数“PARENT_TEMPLATE”解析为接口父级?
【问题讨论】:
-
由于类型擦除,这个问题的答案可能是你不能。
-
我想将模板参数名称 PARENT_TEMPLATE 映射到 Interface1
中定义的真实类型 -
我意识到这一点。我只是指出,由于 java 类型擦除,这可能是不可能的
标签: generics kotlin reflection