how can I get corresponding `java.lang.Class` from...
# announcements
p
how can I get corresponding
java.lang.Class
from
kotlin.reflect.KClass
?
p
how could i do it in java?
oh, its an extension function
ok
*extension property
d
JvmClassMapping.getJava(KClass)
should do it
p
yup
thanks man 🙂
d
Eh, * JvmKlassMappingKt
JvmClassMappingKt
p
really? i dont see
JvmKlassMappingKt
but I do see
JvmClassMappingKt
d
That's what I meant. 😄 Sorry
p
hmmm.. not what I needed
d
Hm, what do you need then? 😄
p
maybe i need to broaden my question.. I need to get java class from
KParameter
tried this:
Copy code
JvmClassMappingKt.getJavaClass(kParameter.getType().getClassifier())
but that gives me:
Copy code
class kotlin.reflect.jvm.internal.KClassImpl
instead of
Copy code
class java.util.String
d
getJavaClass
is like
Object#getClass
in Java.
You want
getJava
.
p
cant find this:
Copy code
JvmClassMappingKt.getJava(...)
Copy code
@Suppress("UPPER_BOUND_VIOLATED")
public val <T> KClass<T>.java: Class<T>
    @JvmName("getJavaClass")
    get() = (this as ClassBasedDeclarationContainer).jClass as Class<T>
d
Oh, it has
JvmName
. ...
p
so
.java
is called
getJavaClass
hmm 🤔
d
That's silly, since there is another
getJavaClass
in
JvmClassMapping
which just calls
getClass
.
You must ensure to cast to
KClass
, otherwise you will get the wrong one
JvmClassMappingKt.getJavaClass(((KClass<?>) p.getType().getClassifier()))
🎉 1
With an appropriate check of course, it might not be a
KClass
.
p
this seems to work:
Copy code
JvmClassMappingKt.getJavaClass(JvmClassMappingKt.getKotlinClass(String.class))
gives me
java.lang.String
d
If you don't cast, overload resolution will pick
getJavaClass(Object)
, since
KClassifier
does not satisfy
KClass
.
p
oh nice!
thank you so much
d
No problem