https://kotlinlang.org logo
#reflect
Title
# reflect
m

miha-x64

11/19/2017, 11:15 AM
Any way to get actual type agruments from a reified type? E. g. in
someInlineFunc<A<X>, A<Y>, B<X>>()
, is there a way to say that first two type arguments are different? (Okay, I've resolved my task without it, now it's just a proof-of-concept question.)
s

snrostov

11/19/2017, 11:39 AM
only with
Copy code
inline fun <reified T> typeOf(): Type? {
  val token = object : TypeToken<T>() {}
  return (token.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
}
And there is issue in youtrack, to get type without creating anonymous class for every call.
m

miha-x64

11/19/2017, 12:05 PM
Will compiler create a correct type token anonymous class with all specified type parameters, not for raw type?
s

snrostov

11/19/2017, 12:06 PM
it will create reified types
Copy code
abstract class TypeToken<T>

inline fun <reified T> typeOf(): Type? {
  val token = object : TypeToken<T>() {}
  return (token.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
}

fun main(args: Array<String>) {
  println(typeOf<Int>())
  println(typeOf<List<Int>>())
}
prints
Copy code
class java.lang.Integer
java.util.List<? extends java.lang.Integer>
m

miha-x64

11/19/2017, 12:17 PM
Cool, thanks!
2 Views