我想要做的事情應該非常簡單。我認爲。我想用反射來確定一個case類構造函數的參數名稱和類型。以下是REPL交互。你可以跳到「paramss」被調用的那一端。我想檢查或模式匹配內部列表中的符號,以確定'名稱'確實是一個字符串,'年齡'是一個Int。如何通過Scala中的反射獲得ctor參數類型2.10.1
我該怎麼做?
scala> case class Person(name: String, age: Int)
defined class Person
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
scala> typeOf[Person]
res0: reflect.runtime.universe.Type = Person
scala> typeTag[Person]
res1: reflect.runtime.universe.TypeTag[Person] = TypeTag[Person]
scala> res1.mirror
res2: reflect.runtime.universe.Mirror = JavaMirror with [email protected]4 of type class scala.tools.nsc.interpreter.IMain$TranslatingClassLoader with classpath [(memory)] and parent being [email protected] of type class scala.tools.nsc.util.ScalaClassLoader$URLClassLoader with classpath [file:/Library/Java/JavaVirtualMachines/jdk1.7.0_13.jdk/Contents/Home/jre/lib/resources.jar,file:/Library/Java/JavaVirtualMachines/jdk1.7.0_13.jdk/Contents/Home/jre/lib/rt.jar,file:/Library/Java/JavaVirtualMachines/jdk1.7.0_13.jdk/Contents/Home/jre/lib/jsse.jar,file:/Library/Java/JavaVirtualMachines/jdk1.7.0_13.jdk/Contents/Home/jre/lib/jce.jar,file:/Library/Java/JavaVirtualMachines/jdk1.7.0_13.jdk/Contents/Home/j...
scala> res1.tpe
res3: reflect.runtime.universe.Type = Person
scala> res3.typeSymbol.asClass
res4: reflect.runtime.universe.ClassSymbol = class Person
scala> res2.reflectClass(res4)
res5: reflect.runtime.universe.ClassMirror = class mirror for Person (bound to null)
scala> res3.declaration(reflect.runtime.universe.nme.CONSTRUCTOR)
res6: reflect.runtime.universe.Symbol = constructor Person
scala> res6.asMethod
res7: reflect.runtime.universe.MethodSymbol = constructor Person
scala> res7.paramss
res8: List[List[reflect.runtime.universe.Symbol]] = List(List(value name, value age))
非常感謝。困惑了一陣子。您是否發現除鏈接到ScalaDoc以外的任何文檔? –
有這個斯卡拉反射指南:http://docs.scala-lang.org/overviews/reflection/overview.html我發現這篇相同的指南很有幫助:http://docs.scala-lang .org/overviews/reflection/symbols-trees-types.html但總而言之,所有使用反射和宏的東西都是反覆試驗(偶爾還有一個stackoverflow問題!)。請注意,運行時(而不是宏)反射是非常不重要的線程安全:http://docs.scala-lang.org/overviews/reflection/thread-safety.html我在隨機奇異性上浪費了很多時間'直到我明白了。 –