点击(此处)折叠或打开
- def main(args: Array[String]) {
-
- //从理论上讲,创建一个泛型Array是不可能的,但是可以借助Manifest实现
- //用Manifest[T]的隐式值,保存运行时T的信息,在实际运行时,作为一个参数作用在方法运行的上下文中
- def arrayMake[T : Manifest](first : T, second : T) = {
- val r = new Array[T](2); r(0) = first; r(1) = second; r
- }
- arrayMake(1,2).foreach(println)
-
-
- def mkArray[T : ClassTag](elems: T*) = Array[T](elems: _*)
- mkArray(42, 13).foreach(println)
- mkArray("Japan","Brazil","Germany").foreach(println)
-
- def manif[T](x: List[T])(implicit m: Manifest[T]) = {//原生写法,隐式参数
- if (m <:< manifest[String])
- println("List strings")
- else
- println("Some other type")
- }
-
- manif(List("Spark", "Hadoop")) //运行时,会传入Manifest[String]隐式值
- manif(List(1, 2))
- manif(List("Scala", 3))
-
- val m = manifest[A[String]]
- println(m)
- val cm = classManifest[A[String]]
- println(cm)
- }
在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/