2012-10-11 41 views
21

使用类型标签,我能看到某种类型的参数:在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 = 

格儿......

+0

这里有一个非答案:使用M7至少可以通过转换成一内部获得的类型参数API:'typeOf [List [Int]]。asInstanceOf [scala.reflect.internal.Types $ TypeApiImpl] .typeArguments'。 –

+0

聪明!谢谢。 – Tim

回答

14

可悲的是,我不认为有这将使你的参数的方法,但你可以得到他们抓住这样:

Welcome to Scala version 2.10.0-20121007-145615-65a321c63e (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_35). 
Type in expressions to have them evaluated. 
Type :help for more information. 

scala> import scala.reflect.runtime.universe._ 
import scala.reflect.runtime.universe._ 

scala> typeOf[List[Int]] 
res0: reflect.runtime.universe.Type = scala.List[Int] 

scala> res0 match { case TypeRef(_, _, args) => args } 
res1: List[reflect.runtime.universe.Type] = List(Int) 

scala> res1.head 
res2: reflect.runtime.universe.Type = Int 

编辑 下面就来达到同样的事情稍微更好的方式(以下一个discussion on scala-internals):

scala> res0.asInstanceOf[TypeRefApi].args 
res1: List[reflect.runtime.universe.Type] = List(Int) 
+0

这是在scala-internals邮件列表中讨论的:https://groups.google.com/forum/#!msg/scala-internals/R1iZXfotqds/zqq8QjMJj74J –

+0

似乎这样做! - 虽然(参考你的链接),我也分享你的不安!我在这里指出我自己的经验是为什么这违反了最不惊讶的原则。 – Tim

+0

https://groups.google.com/d/topic/scala-internals/56KRF98Mdjo/discussion –

相关问题