Kotlin: Generics, reflection and the difference be

2019-02-16 15:39发布

问题:

If I try to access the javaClass of a generic type T the Kotlin compiler complains that T is not a subtype of kotlin.Any

class Foo<T> (val t: T ){
    val cls = t.javaClass // Error, T is not a subtype of kotlin.Any
}

If define T as a subtype of Any everything works ok.

class Bar<T:Any> (val t: T ){
    val cls = t.javaClass // OK
}

Q1) If type ´T´ is not a subtype of ´Any´ which class/classes can it be a subtype of ?

Q2) Do a javaClass exist for all instances of T and if so how do I access it ?

回答1:

The default generic upper bound is not Any but Any?.

This also implies that it's not null-safe to get a javaClass from a nullable argument.

To get a javaClass from a generic type instance with Any? upper bound, you can cast it to Any:

val cls = (t as Any).javaClass //unsafe
val clsOrNull = (t as? Any)?.javaClass //safe