lundi 24 février 2020

Kotlin reflect/resolve original type of generic template parameter

How can I figure out which type has generic template parameter?

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
            }

        }
    }
}

Output

tutorial.test.reflection.Interface1

tutorial.test.reflection.Parentable -> PARENT_TEMPLATE false

(it.type?.classifier == Parent::class) should results true. How can I resolve the generic template parameter 'PARENT_TEMPLATE' as the Interface Parent from the inheritance hierarchy?





Aucun commentaire:

Enregistrer un commentaire