If I have a string like "mypackage.MyClass"
, how can I get the corresponding KClass
at runtime (from the JVM)?
If you use Kotlin 1.0, you can convert the obtained Java class to a KClass instance by calling the . kotlin extension property, for example: something. javaClass.
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.
To obtain the reference to a statically known Kotlin class, you can use the class literal syntax: val c = MyClass::class //The reference is a value of type KClass.
You just use typeName of java. lang. Class<T> instead of the qualifiedName of KCLass<T> (more Kotlin-ish) as I've shown in my answer stackoverflow.com/a/45165263/1788806 which was the previously chosen one. @WilliMentzel Your answer is perfect and idiomatic.
You can use Java's method of getting a Class
instance Class.forName
and then convert it to a KClass
using the .kotlin
extension property. The code then looks like this:
val kClass = Class.forName("mypackage.MyClass").kotlin
A more direct way may be added at some point. The issue is located here
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