Hey! Is there a way to know the type of a generic ...
# server
n
Hey! Is there a way to know the type of a generic annotation in runtime? if i have the following:
Copy code
@Target(allowedTargets = [AnnotationTarget.CLASS, AnnotationTarget.FUNCTION])
@Retention(AnnotationRetention.RUNTIME)
annotation class RequiredExternalUserAuth<T>(
    val contextReader: KClass<ContextReader<T>>
)
i want to be able to know what T is in runtime. is it possible?
d
Not without using reflection.
n
with reflection of course
d
I used something like this to get the type parameters of normal classes:
Copy code
fun Any.getGenericSupertypesArgumentClasses(): List<Class<*>> {
    val superType = this::class.java.genericSuperclass as ParameterizedType
    return superType.actualTypeArguments.map { Class.forName(it.typeName) }
}
For annotations you might have to modify it a bit.
n
ahh cool, thanks a lot!
btw - is this the right place to ask this question?
is there a more appropriate place?
d
I think #getting-started would be a better place. But honestly, this isn't much kotlin-specific 🙂
n
umm actually, how is it possible? https://kotlinlang.org/docs/generics.html#type-erasure i see that there is type-erasure in kotlin im kotlin noobie hehe
d
Yes, there's type erasure and therefore you have to use reflection. Also note that in contrast to Java there's a way how to sometimes get the type parameters without reflection: https://kotlinlang.org/docs/inline-functions.html#reified-type-parameters. But that works only for functions, not classes.
n
If there's type-erasure doesnt it mean that the information isn't saved after compilation?
d
Yes, I forgot to mention the documentation for that function 🙂
Copy code
/**
 * If the receiver is a subclass of a generic superclass with type arguments (e.g. `Receiver : Map<Int, String>`)
 * then return the type argument Classes (e.g. `[Int, String]`). Otherwise an exception is thrown.
 */
In other words, this relis on an old Java technique (hack): https://www.baeldung.com/java-generic-type-find-class-runtime#3-using-typetoken