Kotlin get type of generic class without instance

蹲街弑〆低调 提交于 2019-12-10 17:14:09

问题


Hey want go get Type of T , but I can not get it from instance, I have to get it from class parameter, how to do it?

abstract class ViewModelFragment<T : ViewModel>{
    protected lateinit var mViewModel: T

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
       mViewModel = ViewModelProviders
                    .of(scope)
                    .get(getGenericTClass())
    // .get(mViewModel.javaClass) // not working either

   }

   inline fun<reified R> getGenericTClass() = R::class.java

}

Right now compiler complains

Cannot use 'T' as refined class type. Use Class instead.

I've tried to use solution of: https://stackoverflow.com/a/34463352/2163045 but not working for me


回答1:


I have the same issue and code below helped me:

  val persistentClass = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<T>
    mViewModel = ViewModelProviders.of(this, viewModelsFactory).get(persistentClass)


来源:https://stackoverflow.com/questions/47418161/kotlin-get-type-of-generic-class-without-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!