【发布时间】:2019-11-01 03:25:55
【问题描述】:
我有一个多态方法,它将自定义案例类作为类型参数。
现在,为了支持多个案例类(在配置文件中定义为字符串),我需要将字符串转换为案例类的tagType。
为此,我使用runtimeMirror 方法从String 获取类,
然后我用manifestToTypeTag 得到tagType (Getting TypeTag from a classname string)
import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe
import scala.reflect.ManifestFactory
// My polymorphic method
def printMe[T](l: List[T])(implicit typeTag: TypeTag[T]): Unit = println(l)
// This works:
printMe(List("fdfg"))(typeTag[java.lang.String])
// Now, I want to build the typeTag dynamically from a String
val className = "java.lang.String" // a Custom case class
val mirror = universe.runtimeMirror(getClass.getClassLoader)
val cls = Class.forName(className)
// Getting the typeTag from the class name
val t = internal.manifestToTypeTag(mirror,ManifestFactory.classType(cls))
// Call of the method with the generated typeTag
printMe(List("fdfg"))(t)
// Compilation error
Error:(12, 31) type mismatch;
found : scala.reflect.api.Universe#TypeTag[Nothing]
required: reflect.runtime.universe.TypeTag[String]
Note: Nothing <: String, but trait TypeTag is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: String`. (SLS 3.2.10)
printMe(List("fdfg"))(t)
但是,当我将typeTag 传递给我的多态方法时,我得到了如上所示的“类型匹配编译错误”。
确实,我的多态方法需要TypeTag[MyClassToto],而我生成的TypeTag是TypeTag[Nothing]。
我想知道是否可以转换我拥有的TypeTag,或者我可能必须更改我的多态方法的签名?
【问题讨论】:
标签: scala generics reflection