在Scala反射中,如何获取具体子类的泛型类型参数



假设我有一个泛型超类:

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[Example]获得站点,谁能建议我如何获得typeTag[Int]只给出typeTag[Example]?或者没有办法做到这一点,我必须恢复到Java反射?

谢谢你的帮助。

UPDATE:经过一些快速测试,我发现甚至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类(又名按名称调用),以产生方法的结果。因此,scala方法的类型只在这个级别上解决,当方法已经分解为method &NullaryMethod签名。

结果很明显,只能使用递归获得结果类型:

  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是拥有该方法的类,symbol是通过scala反射从Type.member(s)获得的

最新更新