kotlin t class.java,Kotlin:泛型,反思和T和T之间的区别:任何

在Kotlin中,尝试访问泛型类型T的Java类时,若未指定T为Any的子类型,编译器会报错。默认的泛型上限是Any?,这意味着可能存在空安全问题。要安全地获取泛型实例的Java类,可以将T转换为Any,然后调用javaClass。对于非Any类型的T,它可能属于哪些类的子类型?如何在保证安全性的前提下访问其Java类?本文将探讨这些问题及其解决方案。
摘要由CSDN通过智能技术生成

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 (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 (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 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值