Kotlin使用通用化获取泛型类型类 [英] Kotlin get generic type class using reified
问题描述
我刚开始使用Kotlin而不是Java,但我正努力进行可靠的工作来检索泛型类型类.这是我的用例
I just started using Kotlin instead of Java and i'm struggling to make refied work to retrieve a generic type class. Here my use case
abstract class BaseDataFragment<VM : BaseViewModel> : BaseFragment()
{
@Inject
protected lateinit var viewModelProvider: ViewModelProvider
protected lateinit var viewModel: VM
@CallSuper
override fun init(savedInstanceState: Bundle?)
{
viewModel = viewModelProvider.get(getViewModelClass())
}
private inline fun <reified T : ViewModel> getViewModelClass():Class<T> = T::class.java
}
不幸的是,我从getViewModelClass()
收到错误消息:
Unfortunately i get an error from getViewModelClass()
:
不能将"VM"用作已类型化参数.改用类.
Cannot use 'VM' as reified type parameter. Use a class instead.
反正有办法使它正常工作吗?
Is there anyway to make it work?
推荐答案
reified
并不是用于类型擦除的神奇解决方法. JVM上的泛型类的实例不包含有关实例化其类型参数的任何信息.因为信息不存在,所以不能使用reified
来访问它.
reified
is not a magical workaround for type erasure. An instance of a generic class on the JVM does not carry any information about the type parameter it was instantiated with. Because the information is not there, reified
cannot be used to access it.
reified
仅在编译时在调用站点知道类型信息的情况下才有效,而在这种情况下不是这样.
reified
only works when the type information is known at the call site at compile time, which is not the case here.
如果您希望做到这一点,则需要将Class
或KClass
作为类的属性存储,或者实际上是创建用于获取Class
或KClass
实例的虚拟方法.每个派生类.
If you want to be able to do that, you need to store a Class
or KClass
as a property of your class, or indeed to create a virtual method for obtaining the Class
or KClass
instance for each derived class.
这篇关于Kotlin使用通用化获取泛型类型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!