在Scala反射中,为什么TypeTag上的反射功能仍然具有类型擦除? [英] In Scala reflection, why reflection function on TypeTag still has type erasure?

查看:187
本文介绍了在Scala反射中,为什么TypeTag上的反射功能仍然具有类型擦除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下scala程序:

Considering the following scala program:

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",但是在这种情况下,我得到了以下程序输出:

Since TypeTag has both Seq and String information, I would expect that fn.returnType give the correct result "String", but in this case I got the following program output:

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'

Obviously type String was erased, leaving only a wildcard type 'A'

为什么TypeTag无法产生预期的正确擦除类型?

Why TypeTag is unable to yield the correct erased type as intended?

推荐答案

Seq.head被定义为def head: A.而fn只是通用类Seq[A]中方法head的方法符号,它对具体类型一无所知.因此,它的returnType正是Seq中定义的A.

Seq.head is defined as def head: A. And fn is just a method symbol of the method head from a generic class Seq[A], it doesn't know anything about the concrete type. So its returnType is exactly that A just as defined in Seq.

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

If you want to know what that A would be in some concrete Type, you'd have to specify that explicitly. For instance, you can use infoIn on the method symbol:

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

scala> val fnRetTp = fnTp.resultType
fnRetTp: reflect.runtime.universe.Type = String

这篇关于在Scala反射中,为什么TypeTag上的反射功能仍然具有类型擦除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆