kotlin - 获取 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")
}
解决方案
推荐阅读
- vba - MS Access - 导出页面设置
- c# - Xamarin Forms BindableProperty 创建抛出 TypeInitializationException
- python - 如何为 Python 的新 NamedTuple 类型定义构造函数?
- android - Android Studio SDK 无法下载
- javascript - 为什么无法在我的本地 apache2 服务器中加载 js 文件?
- android - 使用 seekbar 更改 imageView 背景的可绘制颜色
- mysql - 我无法登录基于 Prestashop 1.7 的电子商店。(数据库中没有 ps_employee 表。)
- c++ - 包罗万象的处理程序检测 C++ 中的子类异常
- c# - 获取 User.identity 的名字和姓氏
- ios - iPhone X 中的对齐问题