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

标签 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

最佳答案

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

关于scala - 如何找到祖先类的类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24248979/

相关文章:

scala - 在scala中输出 map 值的问题

java - 从 Scala 到 Java 多线程的 Akka actor 教程

algorithm - 简单循环太慢

oop - 使用反射是否被认为是不面向对象的?

c# - 为非托管程序集动态创建包装器?

scala - 如何在使用 git 库的 IntelliJ IDEA 中设置 scala 项目

html - 如何清除子元素的所有样式?

c++ - 如何通过基类指针获取子类的属性

c# - 覆盖被覆盖的方法 (C#)

c# - 在 C#/Silverlight 应用程序中使用反射访问私有(private)方法