Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin get type of generic class without instance

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

like image 224
murt Avatar asked Nov 21 '17 16:11

murt


People also ask

How do I find my generic class type Kotlin?

There are no direct ways to do this in Kotlin. In order to check the generic type, we need to create an instance of the generic class<T> and then we can compare the same with our class.

Can a generic class be subclass of non generic?

A generic class can extend a non-generic class.

What is KClass Kotlin?

The KClass type is Kotlin's counterpart to Java's java. lang. Class type. It's used to hold references to Kotlin classes; you'll see what it lets you do with those classes in the “Reflection” section later in this chapter. The type parameter of KClass specifies which Kotlin classes can be referred to by this reference.

What is Kotlin reified?

"reified" is a special type of keyword that helps Kotlin developers to access the information related to a class at runtime. "reified" can only be used with inline functions. When "reified" keyword is used, the compiler copies the function's bytecode to every section of the code where the function has been called.


1 Answers

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)
like image 168
Darthoo Avatar answered Sep 25 '22 22:09

Darthoo