使用类型标签,我能看到某种类型的参数:在Scala 2.10中通过反射查找类型参数?
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
scala> typeOf[List[Int]]
res0: reflect.runtime.universe.Type = List[Int]
但我不能完全弄清楚如何以编程方式获取“内部”离开那里,在一般的方式。我已经在REPL中四处游荡了一段时间,试图在Type上进行排列,看看我能从它得到什么......我得到很多表明这是“List”的东西,但是祝你好运找到“诠释”!我真的不想诉诸解析toString()输出...)
丹尼尔索布拉尔有一个很好的(像往常一样)快速概述here,他在其中功亏一篑我正在寻找,但(显然)假如你碰巧知道,对于特定类,可以询问一些具体的方法,其类型:
scala> res0.member(newTermName("head"))
res1: reflect.runtime.universe.Symbol = method head
scala> res1.typeSignatureIn(res0)
res2: reflect.runtime.universe.Type = => Int
但我希望有更通用的东西,它不涉及在声明的方法列表中生根,并希望其中一个将捕获(并因此泄漏)标记的当前类型信息。
如果斯卡拉可以这么容易打印“列表[Int]”,为什么地球上很难发现“Int”部分 - 而不诉诸字符串模式匹配?或者我只是错过了一些真的,真的很明显?
scala> res0.typeSymbol.asInstanceOf[ClassSymbol].typeParams
res12: List[reflect.runtime.universe.Symbol] = List(type A)
scala> res12.head.typeSignatureIn(res0)
res13: reflect.runtime.universe.Type =
格儿......
这里有一个非答案:使用M7至少可以通过转换成一内部获得的类型参数API:'typeOf [List [Int]]。asInstanceOf [scala.reflect.internal.Types $ TypeApiImpl] .typeArguments'。 –
聪明!谢谢。 – Tim