0

I want to get the class name of the class pass-in into a generic class

class GernericClass<T> {
  fun printOut() {
    println(T::class.java.name) // I want something like this

  }
}

This is my main function

fun main() {
  val className = GernericClass<SomeObjectClass>()
  className.printOut() // wanted output: SomeObjectClass
}

Is it possible to get the class name only by calling GernericClass<SomeObjectClass>()

NhatHo
  • 61
  • 9
  • Probably, this question is a duplicate of this one; https://stackoverflow.com/questions/34122450/how-to-get-generic-parameter-class-in-kotlin – MrYakar Mar 24 '22 at 06:16
  • 2
    Does this answer your question? [How to get generic parameter class in Kotlin](https://stackoverflow.com/questions/34122450/how-to-get-generic-parameter-class-in-kotlin) – Karsten Gabriel Mar 24 '22 at 09:21

1 Answers1

0

Need a subclass to specify the type of T, because of generic erasure,

fun main() {
  val className = object:GernericClass<SomeObjectClass>(){}
  className.printOut()  
}
  fun printOut() {
        val clazz =
            (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<*>
        println(clazz) // I want something like this
    }
Tiejun She
  • 79
  • 3
  • Hi there, can you explain to me the object:GernericClass(){}. I'm a little bit lost in this line. If you have some link that I can read it from then it will be very useful. Thanks you – NhatHo Mar 27 '22 at 09:04
  • The generic objects themselves are just the raw type, the parameterized type is "erased" So, need a subclass to specify the type of T. object:GernericClass(){}// anonymous class – Tiejun She Mar 28 '22 at 08:43