如何获取Generic类的类型并将对象强制转换为它?
我想使用此函数来传递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)