你如何找到祖先类的类型参数?

时间:2014-06-16 17:23:45

标签: scala inheritance reflection

如何找到继承类的类型参数?

为了说明这些定义:

// Scala 2.11.1
class DerivedClass extends Function1[Int, String] {
  def apply(i: Int): String = "Zep"
}

def printTypeInfo(typ: Type) {
  println(typ.typeSymbol)
  println(s"  typeArgs=${typ.typeArgs}")
  typ match {
    case TypeRef(prefix, symbol, args) =>
      println(s"  TypeRef($prefix, $symbol, $args")
    case _ =>
      println(s"  no match")
  }
  println
}

打印叶节点类的类型参数:

  printTypeInfo(weakTypeOf[DerivedClass])
  printTypeInfo(weakTypeOf[Function1[Int, String]])

工作正常,产生这个输出:

class DerivedClass
  typeArgs=List()
  TypeRef(A.type, class DerivedClass, List()

trait Function1
  typeArgs=List(Int, String)
  TypeRef(scala.type, trait Function1, List(Int, String)

但同样的方法适用于.baseClasses

weakTypeOf[DerivedClass].baseClasses.foreach(sym =>
  printTypeInfo(sym.typeSignatureIn(weakTypeOf[DerivedClass])))

丢失了类型参数:

class DerivedClass
  typeArgs=List()
  no match

trait Function1
  typeArgs=List()
  no match

class Object
  typeArgs=List()
  no match

class Any
  typeArgs=List()
  no match

1 个答案:

答案 0 :(得分:3)

import scala.reflect.runtime.universe._

val TypeRef(_, _, List(from, to)) = 
  typeOf[DerivedClass].baseType(typeOf[Function1[_,_]].typeSymbol)

结果:

from: reflect.runtime.universe.Type = scala.Int
to: reflect.runtime.universe.Type = String