考虑以下scala程序:
val arr: Seq[String] = Seq("abc", "def")
val cls = arr.head.getClass
println(cls)
val ttg: TypeTag[Seq[String]] = typeOf[Seq[String]]
val fns = ttg.tpe
.members
val fn = fns
.filter(_.name.toString == "head")
.head // Unsafely access it for now, use Option and map under normal conditions
.asMethod // Coerce to a method symbol
val fnTp = fn.returnType
println(fnTp)
val fnCls = ttg.mirror.runtimeClass(fnTp)
assert(fnTp == cls)
由于 TypeTag 同时具有 Seq 和 String 信息,我希望fn.returnType
给出正确的结果“String”,但在这种情况下,我得到了以下程序输出:
cls = class java.lang.String
fnTp = A
随后抛出此异常:
A needed class was not found. This could be due to an error in your runpath. Missing class: no Java class corresponding to A found
java.lang.NoClassDefFoundError: no Java class corresponding to A found
at scala.reflect.runtime.JavaMirrors$JavaMirror.typeToJavaClass(JavaMirrors.scala:1258)
at scala.reflect.runtime.JavaMirrors$JavaMirror.runtimeClass(JavaMirrors.scala:202)
at scala.reflect.runtime.JavaMirrors$JavaMirror.runtimeClass(JavaMirrors.scala:65)
显然 String 类型被删除了,只留下一个通配符类型 'A'
为什么 TypeTag 无法按预期产生正确的擦除类型?