2012-10-11 42 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 –

相關問題