Best way to find generic type of implemented interface?

I have the following situation:

interface MyInterface<T>

class MyClass : MyInterface<String>

In this simple constellation I can find out the generic type String like this:

val para = myClass.javaClass.genericInterfaces[0] as ParametrizedType
val genericClass = para.actualTypeArguments[0] as Class<*>

However, the solution is quite brittle, e.g. when multiple interfaces are implemented, or if MyInterface is only an indirect superinterface. Is there a better way to write this, e.g. by specifying the interface directly I want to investigate further? Or is there some utility class?

I suggest using Kotlin reflection instead of Java reflection as it is cross-platform and more native to Kotlin.

Also, I’m not sure how to solve your problem using Java reflection, it may require additional work to traverse the types tree, but with Kotlin reflection this is relatively easy to do:

val base = MyClass::class.allSupertypes.single { it.classifier == MyInterface::class }
val type = base.arguments[0].type

I believe it should correctly handle all cases.

Also, remember about this case:

class MyClass<T> : MyInterface<T>

In this case type returned by the above code won’t be any specific type, but a type param (type.classifier will be KTypeParameter)

1 Like

Thank you, I’ll use this version.