0

I have a class like this

class Box<T>(t: T) {
    var value = t
    var classType = T::class.java --Not working
}

var box = Box<Int>(1)

Inside the class, how can I find what class type is passed in generic class. For example in the above, I want to find that Integer is passed.

UserJ
  • 230
  • 2
  • 14
  • What do you mean by "what _kind_ of class value"? Surely you don't mean this [kind](https://en.wikipedia.org/wiki/Kind_(type_theory)), right? – Sweeper May 01 '20 at 14:24

1 Answers1

1

You have two possibilities without relying on reflection depending on your needs:

1. Get the class of your instance of type T making the upper bound of T as Any

class Box<T: Any>(t: T) {
    var value = t
    var classType = t::class.java
}

This has two limitations:

  • it doesn't return the precise type passed when creating the class but the type of the instance of T which can be a subtype of T
  • it doesn't support nullable types

2. Simulate the constructor reifing the type parameter in an operator fun

class Box<T>(t: T, private val classType: Class<out T>) {
    var value = t

    companion object {
        inline operator fun <reified T> invoke(t: T): Box<T> = Box(t, T::class.java)
    }
}

This solution solves the two problems above.

Giorgio Antonioli
  • 15,771
  • 10
  • 45
  • 70