首页 > 解决方案 > 获取 kotlin 密封的类名层次结构

问题描述

我写了一个脏函数,它给了我一个密封的类层次结构的名称结构。它很糟糕,因为它使用反射 - 所以我问是否有更好的非反射方式。

fun KClass<*>.sealedClassName(): String {
    var className = simpleName
    var sealedParent = superclasses.firstOrNull { it.isSealed }
    while (sealedParent != null) {
        className = "${sealedParent.simpleName}.$className"
        sealedParent = sealedParent.superclasses.firstOrNull { it.isSealed }
    }
    return className ?: qualifiedName ?: jvmName
}

    interface AnInterface
    open class AnClass
    sealed class Grandparent : AnClass(), AnInterface {
        sealed class Parent : Grandparent(), AnInterface {
            object Child : Parent()
        }

        object AuntieObject : Grandparent()
        data class UncleData(val x: Int) : Grandparent()
    }

    @Test
    fun sealedClassName() {
        check(Grandparent.Parent::class, "Grandparent.Parent")
        check(Grandparent.AuntieObject::class, "Grandparent.AuntieObject")
        check(Grandparent.UncleData::class, "Grandparent.UncleData")
        check(Grandparent.Parent.Child::class, "Grandparent.Parent.Child")
        check(Unit::class, "Unit")
    }

标签: kotlin

解决方案


推荐阅读