Is there a reliable way to determine the class of ...
# getting-started
l
Is there a reliable way to determine the class of a reified generic, including typedefs? I tried a when(T::class), but I can’t use X::class when X is a typedef. I would like to distinguish X and Y, where X and Y are both typedefs for class Z.
The reason is that I’m writing a helper method for JNI methods. I need the signature of a method, so I am using reified generics in an inline method for this. I can check T::class against Int::class, Double::class, etc to get the proper signature. I can’t check against jstring/jobject, however, since both are typedefs for CPointers.
e
the problem with
KClass
is generic erasure, not typedef. try
KType
,
Copy code
typeOf<X>()
l
I’ll take a look at that.
Is there a performance hit due to reflection? I should mention this is K/N, so I don’t know as much about reflection on K/N.
e
on JVM it does result in some kotlin-reflect machinery being loaded, but I don't know about K/N
l
I’ll have to try this out tonight and see if it helps.
I tried using a when with typeOf, but when I pass in a typeOf a typedef, it always triggers the when branch with the first type that has the same underlying class. If I have
Copy code
when(type) {
    typeOf<jstring> -> "String"
    typeOf<jobject> -> "Object"
}
and pass in typeOf<jobject>, it returns “String”
where jstring and jobject are both typedefs for CPointer
e
oh, I see. there is
typedef jobject jstring
in
jni.h
. so they are 100% indistinguishable in C and in Kotlin.
l
Yeah. I'm trying to write a method that uses reified generics to automatically get the signature of a method. I have it working for everything except typedefs. The Kotlin signature is known at compile time, I just want to create a string using it.
e
typedef
doesn't really exist, you can think of every usage as being immediately substituted before compilation
l
Yeah. I may need to make some sort of compiler plugin