Kotlin:泛型,反思和T和T之间的区别:任何 [英] Kotlin: Generics, reflection and the difference between type T and T:Any
问题描述
如果我尝试访问泛型类型T的javaClass,Kotlin编译器会抱怨T不是kotlin.Any的子类型。
class Foo< T> (val t:T){
$ p
val cls = t.javaClass //错误,T不是kotlin.Any的子类型
}
如果将T定义为子类型,任何一切都可以正常工作。
class Bar< T:Any> (val t:T){
val cls = t.javaClass // OK
}
$ b $ Q1)如果类型'T'不是'任何'的子类型,哪个类/类可以成为子类? Q2)对于T的所有实例是否存在一个javaClass,如果有,我该如何访问它? 泛型上界不是任何
但是任何?
p>
这也意味着从一个可为null的参数获取
javaClass
不是无效的。
要从具有
Any?
上限的泛型类型实例获取javaClass
你可以将它转换为任何
:
val cls =(t as任何).javaClass //不安全
val clsOrNull =(t as?Any)?. javaClass // safe
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 ?
解决方案The default generic upper bound is not
Any
butAny?
.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 withAny?
upper bound, you can cast it toAny
:val cls = (t as Any).javaClass //unsafe val clsOrNull = (t as? Any)?.javaClass //safe
这篇关于Kotlin:泛型,反思和T和T之间的区别:任何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!