在运行时scala中将Type传递给具有泛型的类



我有一个类:

class MyClass[T <: AnyRef : Manifest](implicit classTagT: ClassTag[T]) {
 ...
 }

我有一个变量:

val t: Type = typeOf[...]

我该怎么做:

val c = new MyClass[t]

首先,Manifest扩展了ClassTag,因此声明看起来可疑。您可能想要删除其中一个或另一个(如果可能的话,最好是Manifest)。

其次,你不能完全按照自己的意愿去做。但是,您可以从Type构造ClassTagManifest,并手动传递(正如@stefanobaghino所指出的,如果您从typeOf[...]获得t,则不需要这样做)。大约(未经测试):

val t: Type = ...
val clazz = scala.reflect.runtime.currentMirror.runtimeClass(t)
ManifestFactory.classType(clazz) match {
  case m: Manifest[a] =>
    val c = new MyClass(m, m)
}

最新更新