简体   繁体   中英

Get runtime class of a generic type parameter in Kotlin without reified keyword

Kotlin provides a way to get runtime class of a generic type parameter with reified keyword which can only be used with inline functions. For example the following works:

inline fun <reified T> test() : T {
  println(T::class.java)
}

However, I need a way of doing this in a non-inline function. Since the reified keyword is not an option for non-inline functions, the following does not work:

fun <reified T> test() : T {
  println(T::class.java)
}

Does Kotlin have a different method to solve this problem? I know taking the Class<T> as a parameter can be a solution but I don't want to pass an extra argument to my function for this purpose.

A somewhat tricky solution:

inline fun <reified T> test() : T = testImpl(T::class.java)
private fun <T> testImpl(`class`: Class<T>) : T {
  println(`class`)
  // do something
}

In this solution you're actually passing a Class instance but you are not doing it directly. Your invocation code will probably look like test<Xxx>() .
If T of test can be inferred, you can use test() directly, and the generic parameter is still passed correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM