一、ClassTag 、Manifest、ClassManifest、TypeTag代码实战
package ce.scala.zhong
object Multiple_Bounds_46 {
def main(args: Array[String]): Unit = {
//常见写法(推荐)
def arrayMake[T : Manifest](first : T, second : T) = { //创建泛型数组,理论上不可以,因为没有指定具体的类型。运行时,数组必须有具体的类型。
//Array只是Scala的一个普通的类,在虚拟机中,泛型相关的类型信息是被抹掉的。只会有一个arrayMake方法,却要处理所有类型T
//Manifest来帮我们存储运行时的T的具体信息,实际运行时,作为参数用在方法运行的上下文中。当然这个是隐式的过程
//[T : Manifest]是Manifest上下文界定。有这样的隐式值Manifest[T]来辅助构建Array[T],从而确定数组类型
val r = new Array[T](2)
r(0) = first
r(1) = second
r
}
//原始写法(不推荐)
def manif[T](x : List[T])(implicit m : Manifest[T]) = {
if(m <:< manifest[String]) println("List String") //<:<意思是m是manifest[String]的类型
else println("some other type")
}
manif