使用下面的代碼,new Box(10), new Box("20")
對我很好。但對於new Box(Seq(20)), new Box(Seq("20")))
, 我想弄清楚的序列類型參數的類型,這樣我就可以打印序列[INT],SEQ [字符串]如何確定嵌套類型參數的類型參數
@Test
def testClassTag(): Unit = {
class Box[T:ClassTag](val data: T) {
def printTypeParameter() = {
val tag = implicitly[ClassTag[T]].runtimeClass
tag match {
case _ if tag == classOf[Int] => println("Int")
case _ if tag == classOf[String] => println("String")
case _ if tag == classOf[Seq[_]] => println("Seq")
}
}
}
val boxes = Seq(new Box(10), new Box("20"), new Box(Seq(20)), new Box(Seq("20")))
boxes.foreach(_.printTypeParameter())
}
感謝@dima的答案! – Tom