Finding the type parameter class of generic parent class at runtime

Hi,
what I want to do is as written in the title: find the type parameter used to define a class that inherits a generic class/interface

say we have this generic class

abstract class AbstractClass<T>

I’d like to get T, from a KClass object of a child class
ex)

class ChildClass : AbstractClass<Int>

I did find a solution using javaType, but I want to know if there’s a better option, since it requires the @OptIn(ExperimentalStdlibApi::class) annotation
sol)

val kclass = KClass<ChildClass>
val type = kclass.allSupertypes.first { superType -> superType.classifier == AbstractClass::class }
val targetClass = (type.javaType as ParameterizedType).actualTypeArguments.first()
(targetClass as Class<*>).kotlin

You was almost there:

val baseType = ChildClass::class.allSupertypes.first { it.classifier == AbstractClass::class }
val typeParam = baseType.arguments.first().type
println(typeParam) // kotlin.Int
1 Like