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
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.
A generic class can extend a non-generic class.
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.
"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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With