Any simple way to get java.lang.reflect.Type object of reified type?


#1

Consider this code:

import java.lang.reflect.ParameterizedType

fun main(args: Array<String>) {
    demoReified<List<String>>()
}

inline fun <reified T> demoReified() {
    println(T::class.java)   // Outputs type, but with no type parameters.

    val obj = object : WrapGeneric<T>() {}
    val javaClass = obj.javaClass
    val parameterizedType = javaClass.genericSuperclass as ParameterizedType
    val inputType = parameterizedType.actualTypeArguments[0]
    println(inputType)     // Outputs type with parameters.
}

open class WrapGeneric<T>

This code does work, but it creates a class wherever the function is called, which seems very heavy. Is there a better way to get type parameter information?


#2

In general there is no better way. However in case where you know more about the type you can actually use a second generic type parameter for the value. As getting the generic parameter implies that you know more about the type that may be the solution. You can also overload it for specific frequent types and use the current version as a fallback overload.