为什么isInstanceOf[T]
方法无法按预期工作?
以下,我定义了一个hello
类和伴随对象。在hello对象中,我在代码“ this.isInstanceOf[T]
”的行中测试hel.typetest[Int]
,当类型true
为T
时,这是什么Int
?
import scala.reflect.ClassTag
object hello {
def main(args: Array[String]): Unit = {
Console.println("main")
val hel = new hello
hel.typetest[Int]
}
}
class hello {
def typetest[T: ClassTag]: Unit = {
Console.println(this.isInstanceOf[T])
Console.println(this.getClass)
}
}
输出:
main
true
class hello
由于type erasure(连同拳击)。 T
会擦除为Object
,因此this.isInstanceOf[T]
在字节码中始终为true,因此变为this.isInstanceOf[Object]
。
实际上,ClassTag
旨在避免这种情况,但是您需要实际使用它而不是调用isInstanceOf
:
def typetest[T](implicit tag: ClassTag[T]): Unit = {
Console.println(tag.runtimeClass.isInstance(this))
}
[存在T
时,也有针对ClassTag
的模式匹配的特殊情况支持:
def typetest[T: ClassTag]: Unit = {
Console.println(this match {
case _: T => true
case _ => false
})
}