If I have a string like "mypackage.MyClass", how can I get the corresponding KClass at runtime (from the JVM)?
2 Answers
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
4 Comments
Jesse Wilson
Note that this doesn’t work for primitive types like
char.Stephen Talley
It also doesn't work for types auto-converted types like java.util.List, kotlin.collections.Collection, kotlin.collections.Iterable, kotlin.Any, etc. To get a KClass for those types, you need to call Class.forName() with their Java counterparts (java.util.List, java.util.Collection, java.lang.Iterable, java.lang.Object). This is obviously not an exhaustive list.
Dan Lugg
@StephenTalley I noticed this too;
kotlin.Any -> java.lang.Object -- seems the only workaround is a userland function of forName that validates/maps the Kotlin-world naming to Java.Askcomp eugi-tech
Does it work for external app, if I have its pakage name?
There is no possibility using only Kotlin Reflection.
There are two methods via Java Reflection:
//executes: load, link, and initialize phases
val kClass = Class.forName("mypackage.MyClass").kotlin
//executes: load and link phases
val kClass = ClassLoader.getSystemClassLoader().loadClass("mypackage.MyClass").kotlin
This does not work for primitive types and Koltin synonyms. Example for Integer:
- int
- kotlin.Int
use java.lang.Integer.