Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert java Class<> to kotlin's KClass<>

Tags:

java

kotlin

like I hava a kotlin function:

object KotlinFunc {
    @JvmStatic
    fun create(mycls: KClass<*>) {...}
}

I want to invoke this function in java code, but this not working:

public void javaFunc() {
   KotlinFunc.create(MyClass.class)
}
like image 870
Ted Avatar asked Mar 27 '19 03:03

Ted


1 Answers

It is possible by using calling the getKotlinClass function in Java:

kotlin.jvm.JvmClassMappingKt.getKotlinClass(MyClass.class);

you can invoke your function like this:

kotlin.reflect.KClass<MyClass> kClass = kotlin.jvm.JvmClassMappingKt.getKotlinClass(MyClass.class);
KotlinFunc.create(kClass);

and make sure that kotlin-reflect is in your classpath, e.g.:

with Gradle Kotlin:

dependencies {
    ...
    implementation(kotlin("reflect"))
    ...
}

with Gradle Groovy:

dependencies {
    ...
    implementation 'org.jetbrains.kotlin:kotlin-reflect'
    ...
}
like image 193
birneee Avatar answered Sep 23 '22 17:09

birneee