如何迭代类层次结构?

时间:2016-03-07 12:03:24

标签: kotlin

我想迭代类层次结构并打印所有超类:

git merge --no-ff some-work

但Kotlin open class A {} open class B : A() {} open class C : B() {} fun main(args: Array<String>) { var currentClass = C::class while(currentClass != Any::class) { println(currentClass) currentClass = currentClass.superclass } } 没有KClass方法。

我尝试过使用Java中的superclass

superclass

但它会导致编译错误:

 currentClass = currentClass.java.superclass.kotlin

那么,有人可以解释我该怎么做吗?

1 个答案:

答案 0 :(得分:7)

首先,为var currentClass指定显式类型,以避免将其推断为KClass<C>

var currentClass: KClass<*> = C::class

然后,superclass来电将返回with in projection类型,您无法在其上调用.kotlin。因此,转换为star-projected类型也会有所帮助:

currentClass = (currentClass.java.superclass as Class<*>).kotlin

完整方法:

fun main(args: Array<String>) {
    var currentClass: KClass<*> = C::class
    while (currentClass != Any::class) {
        println(currentClass)
        currentClass = (currentClass.java.superclass as Class<*>).kotlin
    }
}