Kotlin语言在运行时获取类 [英] Kotlin language get class at runtime
问题描述
假设我们有以下内容:
val person = "Bill"
有人可以解释一下两者之间的区别吗?
Could someone explain the difference between these two:
val kClass1 = person.javaClass.kotlin
与
val kClass2 = person::class
什么时候我应该打一个而不是另一个?
When I should call the one instead of the other?
任何源代码示例都将不胜感激.
Any source code example would be appreciated.
推荐答案
有两种方法可以实现相同的目的,即获取对象的Kotlin类,是因为在Kotlin 1.1之前,::class
文字不支持其左侧的表达式.因此,如果您使用的是Kotlin 1.0,则唯一的选择是.javaClass.kotlin
,否则您都可以使用它们.这就是"Kotlin in Action"使用.javaClass.kotlin
语法的原因:它是在Kotlin 1.1发行版之前编写的.
The main reason there are two ways to achieve the same thing, namely get the Kotlin class of an object, is because prior to Kotlin 1.1, the ::class
literal did not support the expression on its left-hand side. So if you're using Kotlin 1.0, your only option is .javaClass.kotlin
, otherwise you're fine with either of them. This is the reason "Kotlin in Action" uses the .javaClass.kotlin
syntax: it was written before the Kotlin 1.1 release.
这些表达式的类型也略有不同.例如,在以下代码中
There's also a minor difference in the types of these expressions. For example, in the following code
interface T
fun f1(x: T) = x::class
fun f2(x: T) = x.javaClass.kotlin
f1
的类型为KClass<out T>
,但是f2
的类型为KClass<T>
.这实际上是对javaClass
声明的疏忽:在这种情况下,KClass<out T>
更正确,因为x
的类不一定是T
,但也可以是T
的子类.
f1
's type is KClass<out T>
, but f2
's type is KClass<T>
. This is actually an oversight in the javaClass
declaration: KClass<out T>
is more correct in this case, because x
's class is not necessarily T
, but can also be a subclass of T
.
否则,这两个表达式(x.javaClass.kotlin
和x::class
)在产生的字节码和运行时性能方面是完全等效的.我更喜欢x::class
,因为它更短并且读起来更好.
Otherwise these two expressions (x.javaClass.kotlin
and x::class
) are completely equivalent in terms of produced bytecode and runtime performance. I prefer x::class
because it's shorter and reads better.
这篇关于Kotlin语言在运行时获取类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!