ClassTag、Manifest、ClassManifest、TypeTag


点击(此处)折叠或打开

  1. def main(args: Array[String]) {
  2.    
  3.     //从理论上讲,创建一个泛型Array是不可能的,但是可以借助Manifest实现
  4.     //用Manifest[T]的隐式值,保存运行时T的信息,在实际运行时,作为一个参数作用在方法运行的上下文中
  5.     def arrayMake[T : Manifest](first : T, second : T) = {
  6.       val r = new Array[T](2); r(0) = first; r(1) = second; r
  7.     }
  8.    arrayMake(1,2).foreach(println)
  9.   
  10.     
  11.    def mkArray[T : ClassTag](elems: T*) = Array[T](elems: _*)
  12.    mkArray(42, 13).foreach(println)
  13.    mkArray("Japan","Brazil","Germany").foreach(println)
  14.     
  15.     def manif[T](x: List[T])(implicit m: Manifest[T]) = {//原生写法,隐式参数
  16.      if (m <:< manifest[String])
  17.      println("List strings")
  18.      else
  19.      println("Some other type")
  20.     }

  21.     manif(List("Spark", "Hadoop")) //运行时,会传入Manifest[String]隐式值
  22.     manif(List(1, 2))
  23.     manif(List("Scala", 3))
  24.     
  25.     val m = manifest[A[String]]
  26.     println(m)
  27.     val cm = classManifest[A[String]]
  28.     println(cm)
  29.   }
由于Manifest在依赖路径判断上存在问题,所以,Scala推出来ClassTag、TypeTag用来取代Manifest、classManifest
在Spark中使用最多的就是ClassTag,ClassTag源码注释:
 * A `ClassTag[T]` stores the erased class of a given type `T`, accessible via the `runtimeClass`
 * field. This is particularly useful for instantiating `Array`s whose element types are unknown
 * at compile time.
  * ClassTag存储T被擦出的class信息,在 不知道元素类型 而初始化Array时特别有用
  *
 * `ClassTag`s are a weaker special case of [[scala.reflect.api.TypeTags#TypeTag]]s, in that they
 * wrap only the runtime class of a given type, whereas a `TypeTag` contains all static type
 * information. That is, `ClassTag`s are constructed from knowing only the top-level class of a
 * type, without necessarily knowing all of its argument types. This runtime information is enough
 * for runtime `Array` creation.
  * ClassTag比TypeTag弱,它只包含运行时class信息,TypeTag包含所有static类型信息

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/28912557/viewspace-1973327/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/28912557/viewspace-1973327/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值