How to get java class from param general parameter?

I am trying to use the following method:

fun <T> put(value: T){
    val clazz = T::class.java
}

but has an exception Kotlin: Only classes are allowed on the left hand side of a class literal

How to get a class from a common parameter?

What other parameters besides the class can be passed as param?

+4
source share
2 answers

fixed using

fun <T: Any> put(value: T){
    val clazz = value.javaClass
}
0
source

To access generic types inside a function, you need to create reified types . Since this is not supported by the JVM, it is only available in the built-in functions:

inline fun <reified T : Any> put(value: T) {
    val clazz = T::class.java
}

Type restriction is Anyrequired to prevent some complications with NULL types.

+7
source

All Articles