Scala 如何找到祖先类的类型参数?
如何找到继承类的类型参数 为了说明,根据这些定义:Scala 如何找到祖先类的类型参数?,scala,inheritance,reflection,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 { c
// 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]])
工作正常,产生以下输出:
类派生类
typeArgs=List()
TypeRef(A.type,class-DerivedClass,List()
特质功能1
typeArgs=List(Int,String)
TypeRef(scala.type,trait Function1,List(Int,String)
但同样的方法也适用于.baseClasses
:
weakTypeOf[DerivedClass].baseClasses.foreach(sym =>
printTypeInfo(sym.typeSignatureIn(weakTypeOf[DerivedClass])))
丢失类型参数:
类派生类
typeArgs=List()
没有对手
特质功能1
typeArgs=List()
没有对手
类对象
typeArgs=List()
没有对手
任何类别
typeArgs=List()
没有对手
结果:
from: reflect.runtime.universe.Type = scala.Int
to: reflect.runtime.universe.Type = String
谢谢。它很有效!我从来没有想到过
Function1[\uu,\u]
。我通过在definitions.FunctionClass.seq
中搜索类型符号,将其推广到任何函数。
from: reflect.runtime.universe.Type = scala.Int
to: reflect.runtime.universe.Type = String