1

考虑以下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 无法按预期产生正确的擦除类型?

4

1 回答 1

3

Seq.head定义为def head: A。而且fn只是head泛型类方法的方法符号Seq[A],它对具体类型一无所知。所以它returnType正是A如 中所定义的那样Seq

如果您想知道A具体的内容是什么,Type则必须明确指定。例如,您可以infoIn在方法符号上使用:

scala> val fnTp = fn.infoIn(ttg.tpe)
fnTp: reflect.runtime.universe.Type = => String

scala> val fnRetTp = fnTp.resultType
fnRetTp: reflect.runtime.universe.Type = String
于 2016-06-09T00:27:06.430 回答