Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a Kotlin KClass from a package class name string?

Tags:

kotlin

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

like image 974
Josh Rosen Avatar asked Dec 17 '15 17:12

Josh Rosen


People also ask

How do you get KClass in Kotlin?

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.

What is KClass in Kotlin?

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.

How do I reference a class in Kotlin?

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.

How do you find the datatype in Kotlin?

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.


1 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

like image 136
Kirill Rakhman Avatar answered Oct 11 '22 19:10

Kirill Rakhman