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.