tri*_*oid 8 generics scala type-erasure scala-reflect
假设我有一个Generic超类:
class GenericExample[T](
                         a: String,
                         b: T
                       ) {
  def fn(i: T): T = b
}
和一个具体的子类:
case class Example(
                    a: String,
                    b: Int
                  ) extends GenericExample[Int](a, b)
我想通过scala反射得到函数"fn"的类型参数,所以我选择并过滤其成员:
import ScalaReflection.universe._
val baseType = typeTag[Example]
val member = baseType
  .tpe
  .member(methodName: TermName)
  .asTerm
  .alternatives
  .map(_.asMethod)
  .head
    val paramss = member.paramss
    val actualTypess: List[List[Type]] = paramss.map {
      params =>
        params.map {
          param =>
            param.typeSignature
        }
    }
我期待scala给我正确的结果List(List(Int)),相反,我只得到了通用List(List(T))
通过文档进行处理我发现typeSignature是罪魁祸首:
 *  This method always returns signatures in the most generic way possible, even if the underlying symbol is obtained from an
 *  instantiation of a generic type.
它建议我使用替代方案:
def typeSignatureIn(site: Type): Type
但是,由于类示例不再是通用的,我无法从typeTag获取站点[示例],任何人都可以建议我如何获取typeOf [Int]仅给出typeTag [示例]?或者没有办法做到这一点我必须恢复到Java反射?
非常感谢你的帮助.
更新:经过一些快速测试后,我发现即使MethodSymbol.returnType也无法按预期工作,以下代码:
member.returnType
也屈服T,并且它无法通过asSeenFrom来纠正,因为以下代码不会改变结果:
member.returnType.asSeenFrom(baseType.tpe, baseType.tpe.typeSymbol.asClass)
我可以建议两种方法:
1)从基类中显示泛型类型:
import scala.reflect.runtime.universe._
class GenericExample[T: TypeTag](a: String, b: T) {
  def fn(i: T) = "" + b + i
}
case class Example(a: String, b: Int) extends GenericExample[Int](a, b) {}
val classType = typeOf[Example].typeSymbol.asClass
val baseClassType = typeOf[GenericExample[_]].typeSymbol.asClass
val baseType = internal.thisType(classType).baseType(baseClassType)
baseType.typeArgs.head // returns reflect.runtime.universe.Type = scala.Int
2)添加返回类型的隐式方法:
import scala.reflect.runtime.universe._
class GenericExample[T](a: String, b: T) {
  def fn(i: T) = "" + b + i
}
case class Example(a: String, b: Int) extends GenericExample[Int](a, b)
implicit class TypeDetector[T: TypeTag](related: GenericExample[T]) {
  def getType(): Type = {
    typeOf[T]
  }
}
new Example("", 1).getType() // returns reflect.runtime.universe.Type = Int
我正在发布我的解决方案:我认为由于 Scala 的设计,没有其他选择:
Scala 反射和 Java 反射中的方法之间的核心区别在于柯里化:Scala 方法由许多对括号组成,首先调用带参数的方法只是构造一个可以接受更多对括号的匿名类,或者如果没有剩下的括号,构造一个 NullaryMethod 类(也称为按名称调用),可以解析该类以产生该方法的结果。因此,当方法已经分解为方法和 NullaryMethod 签名时,scala 方法的类型仅在此级别解析。
结果很明显,结果类型只能使用递归获得:
  private def methodSignatureToParameter_ReturnTypes(tpe: Type): (List[List[Type]], Type) = {
    tpe match {
      case n: NullaryMethodType =>
        Nil -> n.resultType
      case m: MethodType =>
        val paramTypes: List[Type] = m.params.map(_.typeSignatureIn(tpe))
        val downstream = methodSignatureToParameter_ReturnTypes(m.resultType)
        downstream.copy(_1 = List(paramTypes) ++ methodSignatureToParameter_ReturnTypes(m.resultType)._1)
      case _ =>
        Nil -> tpe
    }
  }
  def getParameter_ReturnTypes(symbol: MethodSymbol, impl: Type) = {
    val signature = symbol.typeSignatureIn(impl)
    val result = methodSignatureToParameter_ReturnTypes(signature)
    result
  }
impl拥有该方法的类在哪里,是您通过scala反射symbol获得的Type.member(s)
| 归档时间: | 
 | 
| 查看次数: | 4862 次 | 
| 最近记录: |