I want to get a reference to a runtime KClass of a variable. I went through documentation on classes and reflection, but the documentation seems to only explain how to get a static reference to KClass (e.g. String::class
for String
)
I need a runtime KClass of a variable. This doesn't seem to compile:
fun test(x: Any) {
val klazz = x::class
}
How does one get the KClass
of x
in the example above?
As said in the reference, you can use .javaClass.kotlin
to get KClass
token of an object. Example:
fun printKClass(x: Any) {
val c = x.javaClass.kotlin
println(c)
}
For any further manipulations with the KClass
, you should also add kotlin-reflect
library as a dependency, since the reflection functionality has been moved out of kotlin-stdlib
.
x::class
works fine as long you have kotlin-reflect in your classpath.
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