52

If I have a string like "mypackage.MyClass", how can I get the corresponding KClass at runtime (from the JVM)?

2 Answers 2

87

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

Sign up to request clarification or add additional context in comments.

4 Comments

Note that this doesn’t work for primitive types like char.
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.
@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.
Does it work for external app, if I have its pakage name?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.