清单#runtimeClass了解

时间:2015-02-18 16:16:33

标签: scala

鉴于以下ParentKid

scala> trait Parent[T]
defined trait Parent

scala> case class Kid(clazz: Class[_ <: Parent[_]])
warning: there were 1 feature warning(s); re-run with -feature for details
defined class Kid

现在我想做:

scala> class Foo[A <: Parent[_]](implicit m: scala.reflect.Manifest[A]) {
     |   Kid(m.runtimeClass)
     | }
<console>:11: error: type mismatch;
 found   : Class[_$1(in value <local Foo>)] where type _$1(in value <local Foo>)
 required: Class[_ <: Parent[_]]
         Kid(m.runtimeClass)
               ^

如何从清单中获取Class[_ <: Parent[_]]类型?

1 个答案:

答案 0 :(得分:2)

答案是您必须将通过runtimeClass获得的实例投射到Class的实际实例。

示例:

class Foo[A <: Parent[_]](implicit m: scala.reflect.Manifest[A]) { 
  Kid(m.runtimeClass.asInstanceOf[Class[A]]) 
}

或使用ClassTag

class Foo[A <: Parent[_] : reflect.ClassTag] { 
  Kid(reflect.classTag[A].runtimeClass.asInstanceOf[Class[A]]) 
}

我认为最近在Scala内部讨论过一个类似的话题。相关的问题是Why does the method runtimeClass of ClassTag return a wildcard class?