将字符串转换为typeTag并将其传递给多态方法

3
我有一个多态方法,它的类型参数是自定义的case class。 现在,为了支持多个case class(在配置文件中定义为String),我需要将一个String转换为case class的tagType
为此,我使用了runtimeMirror方法从String获取类, 然后我使用了manifestToTypeTag来获取tagType。(从类名字符串获取TypeTag
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],而我生成的TypeTagTypeTag[Nothing]。我想知道是否有可能强制转换我得到的TypeTag,或者我必须更改我的多态方法的签名?
1个回答

3

尝试来自https://stackoverflow.com/a/23792152/5205022的建议:

最初的回答:

def printMe[T](l: List[T])(implicit typeTag: TypeTag[T]): Unit = println(l)

def stringToTypeTag[A](name: String): TypeTag[A] = {
  val c = Class.forName(name)
  val mirror = runtimeMirror(c.getClassLoader)
  val sym = mirror.staticClass(name)
  val tpe = sym.selfType
  TypeTag(mirror, new api.TypeCreator {
    def apply[U <: api.Universe with Singleton](m: api.Mirror[U]) =
      if (m eq mirror) tpe.asInstanceOf[U # Type]
      else throw new IllegalArgumentException(s"Type tag defined in $mirror cannot be migrated to other mirrors.")
  })
}

printMe(List("fdfg"))(stringToTypeTag("java.lang.String"))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接