How can I get a Java `Class` from a `KClass`? For ...
# announcements
p
How can I get a Java
Class
from a
KClass
? For example I have
Copy code
KClassImpl "class kotlin.String"
and I want to get Java’s
String.class
from it I tried:
Copy code
JvmClassMappingKt.getJavaClass(klass)
but it returns
class kotlin.reflect.jvm.internal.KClassImpl
😕
s
MyClass::class.java
p
I need it at runtime. Not compile time.
j
.java
is a property that works at runtime
p
Oh, I think
.java
is a Kotlin extension property but I have to do this call from Java.
c
You should be able to access that same property from Java code with
JvmClassMappingKt.getJavaClass(aClass);
p
Ok, let me give a full example. I have a simple Kotlin data class and an instance of it in variable
type
. I am trying to get the Java class of the first parameter of the data class’s constructor:
Copy code
KClass<?> klass = JvmClassMappingKt.getKotlinClass(type);
KFunction<?> primaryConstructor = KClasses.getPrimaryConstructor(klass);
List<KParameter> parameters = primaryConstructor.getParameters();
KParameter firstParameter = parameters.get(0);
KType parameterType = firstParameter.getType();
JvmClassMappingKt.getJavaClass(parameterType.getClassifier())
This snippet returns
kotlin.reflect.jvm.internal.KClassImpl
as the result and I would expect
java.lang.String
.
The weird thing is that if I look at the result of
getClassifer()
in debugger I do see the
jClass
there:
Figured it out. It was calling the wrong overload of
getJavaClass
. Changing the last line to:
Copy code
JvmClassMappingKt.getJavaClass((KClass) parameterType.getClassifier());
fixed it.
186 Views