在 Kotlin 中,我可以通过以下方式从
KClass<*>
获取 KType
:Int::class.createType()
如何反向获取表示kotlin.Int的KType,以获得KClass<Int>?KClass<*>
获取 KType
:Int::class.createType()
如何反向获取表示kotlin.Int的KType,以获得KClass<Int>?KType.classifier
进行此操作。val intType : KType = Int::class.createType()
val intClassifier : KClassifier? = intType.classifier
assertEquals(Int::class, intClassifier) // true
注意,自1.3.40版本以来,您还可以(至少在JVM上)使用实验性的typeOf<Int>()
来获取您的KType
。您可能需要查看1.3.40公告,以确定它是否对您有用。
谈到JVM:在JVM上,您还可以使用KType.jvmErasure
来获取实际类,正如marstran在评论中指出的那样。
typeOf<Int>()
的公告...太酷了!基本上是Kotlin中类似于C#中typeof
的等效物。 - Matthew LaytontypeOf<T>()
。实现大概就像这样:inline fun <reified T> typeOf() = T::class.createType()
? - Matthew LaytonSomeType::class.createType()
会丢失关于SomeType
的类型参数和可空性的信息。相比之下,typeOf<SomeType>()
保留了该信息,因为它使用了编译器内部函数,并将类型信息硬编码到字节码中。例如,看一下编译器为typeOf<MutableList<Int?>?>()
生成的字节码。 - hotkey