简体   繁体   English

使用ClassTag和TypeTag获取Seq [AnyRef]元素的类型

[英]Use ClassTag and TypeTag to get type of the elements of Seq[AnyRef]

With the following test case, I would check the type of the elements of a Seq[AnyRef] , 在以下测试案例中,我将检查Seq[AnyRef]的元素类型,

  @Test
  def testClassTagAndTypeTag(): Unit = {
    import scala.reflect.runtime.universe._
    def getTypeTag[T: TypeTag](data: T): TypeTag[T] = typeTag[T]
    def getClassTag[T: ClassTag](data: T): ClassTag[T] = implicitly[ClassTag[T]]
    val data = Seq(List(1), "Hello", new Box(1))
    data.foreach(x => {
      println(s"TypeTag: ${getTypeTag(x)}, tpe: ${getTypeTag(x).tpe}")
    })
    data.foreach(x => {
      println(s"ClassTag: ${getClassTag(x)}")
    })
  }

The output of the above code is: 上面代码的输出是:

TypeTag: TypeTag[java.lang.Object], tpe: java.lang.Object
TypeTag: TypeTag[java.lang.Object], tpe: java.lang.Object
TypeTag: TypeTag[java.lang.Object], tpe: java.lang.Object
ClassTag: Object
ClassTag: Object
ClassTag: Object

I thought that the type tag should output the real type of Seq's elements, which should be 我认为type标签应该输出Seq元素的真实类型,应该是

List[Int]
String
Box[Int]

By the time you have a Seq[AnyRef] , it's too late. 到您拥有Seq[AnyRef] ,为时已晚。 The type of x in data.foreach(x => ...) is just AnyRef , so getTypeTag(x) and getClassTag(x) give corresponding results. data.foreach(x => ...)x的类型仅为AnyRef ,因此getTypeTag(x)getClassTag(x)给出相应的结果。

Instead, you can store type tag together with value, eg 相反,您可以将类型标记与值一起存储,例如

case class WithTypeTag[A](x: A)(implicit val tag: TypeTag[A])

val data = Seq(WithTypeTag(List(1)), WithTypeTag("Hello"), WithTypeTag(new Box(1)))
data.foreach(x => println(x.tag))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM