6

I 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 from this answer but it's not working for me

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
murt
  • 3,790
  • 4
  • 37
  • 48

1 Answers1

2

I have the same issue and the code below helped me:

val persistentClass = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<T>
mViewModel = ViewModelProvider(this, viewModelsFactory).get(persistentClass)
Benny
  • 2,233
  • 1
  • 22
  • 27
Darthoo
  • 301
  • 1
  • 2
  • 14