如何获取通用类的类型并将对象转换为它?
我想用这个函数来传递一个接口(interface)类:
protected fun <T> getInteraction(): T {
return when {
context is T -> context
parentFragment is T -> parentFragment as T
else -> throw IllegalArgumentException("not implemented interaction")
}
}
并像这样使用它:
private var interaction: ISigninInteraction? = null
override fun onAttach(context: Context?) {
super.onAttach(context)
interaction = getInteraction<ISigninInteraction>()
}
最佳答案
Kotlin、Java 和 JVM 在实现泛型时确实有类型删除。泛型在字节码级别是不可见的。这意味着,您不能使用类型参数,例如T
, 直接在函数代码中。
Kotlin 添加了对 reified
的支持泛型,这在这里有帮助。您可以像这样声明函数
inline fun <reified T> getIt() : T {
...
}
在reified
的帮助下和 inline
可以转换为 T
并归还它。
https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters
第二种选择是遵循 Java 实践 - 添加 Class<T>
函数的参数并使用 Class#cast
转换到T
反而。
您可以结合 reified inline
使用如下方法运行:
inline fun <reified T> getIt() = getIt(T::class.java)
关于android - Kotlin : Casting an object to Generic class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55141835/