generics - Kotlin 反射/解析泛型模板参数的原始类型

标签 generics kotlin reflection

如何确定哪种类型具有通用模板参数?

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 false

(it.type?.classifier == Parent::class) 结果应该为 true。如何将通用模板参数“PARENT_TEMPLATE”解析为继承层次结构中的接口(interface)父级?

最佳答案

这是我的解决方案,它有效:

import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.KTypeParameter
import kotlin.reflect.KTypeProjection


private data class SuperType(private val type: KType, val owner: Class) {
    val typeProjections: List<TypeProjection>
        get() = type.arguments.map { TypeProjection(it) }
    val asClass: Class
        get() = Class(type.classifier as KClass<*>, owner)

    fun isTypeOf(cls: KClass<*>) = type.classifier == cls
}

private data class TypeProjection(private val type: KTypeProjection) {
    val isClass: Boolean
        get() = type.type?.classifier is KClass<*>
    val isTemplate: Boolean
        get() = type.type?.classifier is KTypeParameter
    val asClass: KClass<*>
        get() = type.type?.classifier as KClass<*>
    val name: String?
        get() {
            var name: String? = null
            if (isClass)
                name = (type.type?.classifier as KClass<*>).simpleName
            else if (isTemplate)
                name = (type.type?.classifier as KTypeParameter).name
            return name
        }
}

private data class TypeParameter(private val type: KTypeParameter) {
    val name: String
        get() = type.name
}

private data class Class(private val type: KClass<*>, val root: Class? = null) {
    private val supertypes: List<SuperType>
        get() = type.supertypes.filter { it.classifier is KClass<*> && it.classifier != Any::class }
            .map { SuperType(it, this) }
    private val typeParameters: List<TypeParameter>
        get() = type.typeParameters.map { TypeParameter(it) }

    fun findInHierarchy(cls: KClass<*>): Class? {
        for (s in supertypes) {
            if (s.isTypeOf(cls)) {
                return s.asClass;
            } else {
                val s2 = s.asClass.findInHierarchy(cls)
                if (s2 != null)
                    return s2
            }
        }
        return null
    }

    private fun mapTemplateToClass(name: String): KClass<*>? {
        val tp = typeParameters.firstOrNull { it.name == name }
        if (tp != null && root != null) {
            val clsSuperType = root.supertypes.firstOrNull { it.isTypeOf(type) }
            if (clsSuperType != null) {
                val index = typeParameters.indexOf(tp)
                if (index >= 0) {
                    val projection = clsSuperType.typeProjections[index]
                    if (projection.isClass)
                        return projection.asClass
                    else if (projection.isTemplate) {
                        val projectionName = projection.name
                        if (projectionName != null) {
                            return clsSuperType.owner.mapTemplateToClass(projectionName)
                        }
                    }

                }
            }
        }
        return null
    }

    fun resolveAllTemplates(): Map<String, KClass<*>> {
        val paramNames = typeParameters.map { it.name }
        return paramNames.map { it to mapTemplateToClass(it) }.filter { it.second != null }
            .map { it.first to it.second!! }.toMap()
    }
}

fun KClass<*>.resolveTemplates(parent: KClass<*>): Map<String, KClass<*>>? =
    Class(this).findInHierarchy(parent)?.resolveAllTemplates()

interface P1<P1_T1, P1_T2>
interface P2<P2_T1, P2_T2>
interface L1<L_T1, L_T2> : P1<L_T1, L_T2>
interface L2<L_T1, L_T2> : P2<L_T1, L_T2>
interface L3 : L1<Long, String>, L2<String, Any>

fun main(args: Array<String>) {
    var map = L3::class.resolveTemplates(P1::class)
    println(map) // Output: {P1_T1=class kotlin.Long, P1_T2=class kotlin.String}
    map = L3::class.resolveTemplates(P2::class)
    println(map) // Output: {P2_T1=class kotlin.String, P2_T2=class kotlin.Any}
}

关于generics - Kotlin 反射/解析泛型模板参数的原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60374240/

相关文章:

scala - 接受两个monadic值并返回一个monadic值的泛型函数

c# - 抽象方法和泛型方法

c# - 获取作为基类传递给泛型方法的派生 C# 类的属性

android - 由于错误,无法在Firestore中更新阵列

java - 如何反射性地调用以 null 作为参数的方法?

java - 是否可以在 Java 中进行猴子补丁?

typescript - TypeScript 中的通用对象数组

android - 如何使android导航主机与BottomNavigationView一起使用?

android - 字符串中的字符不替换

c# - 为什么开放泛型的基类型不开放?