动态铸造在科特林 [英] Dynamic cast in Kotlin
问题描述
我想使用KClass<Int>
将Any
转换为Int
,同时具有KClass<Int>
和Any
实际上是Int
.
I want to cast Any
to Int
by using KClass<Int>
, having a KClass<Int>
and a Any
which is actually Int
.
fun <T> cast(any: Any, clazz: KClass<*>): T = clazz.java.cast(any)
cast(0, Int::class)
但是,我遇到了这个错误.
However, I got this error.
java.lang.ClassCastException:无法将java.lang.Integer转换为int
java.lang.ClassCastException: Cannot cast java.lang.Integer to int
除了any as Int
以外,您知道其他解决方案吗?
Do you know any solution except any as Int
?
推荐答案
尝试将您的代码更改为
fun <T: Any> cast(any: Any, clazz: KClass<out T>): T = clazz.javaObjectType.cast(any)
说明
由于参数any
的类型为Any
,因此它始终是引用类型,并且将对原语进行装箱.对于第二个参数,看来Kotlin反射将首选原始类型而不是引用类型,这就是为什么Int::class.java
默认为ìnt
而不是Integer
的原因.通过使用javaObjectType
,我们强制使用带框引用类型.
Explanation
Because the type of the parameter any
is Any
, it's always a reference type and primitives will be boxed. For the second parameter, it seems that Kotlin reflection will prefer primitive types to reference types, which is why Int::class.java
will default to ìnt
, not Integer
. By using javaObjectType
we force the usage of the boxed reference type.
您还可以使用以下函数定义:
You could also use the following function definition:
inline fun <reified T: Any> cast(any: Any): T = T::class.javaObjectType.cast(any)
// usage
cast<Int>(0)
这篇关于动态铸造在科特林的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!