我想要做的应该很简单。我认为。我想使用反射来确定案例类构造函数的参数的名称和类型。下面是一个 REPL 交互。您可以跳到调用“paramss”的末尾。我想检查内部列表中的符号或进行模式匹配,以确定“名称”确实是一个字符串,而“年龄”是一个 Int。
我怎么做?
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 scala.tools.nsc.interpreter.IMain$TranslatingClassLoader@2daf73a4 of type class scala.tools.nsc.interpreter.IMain$TranslatingClassLoader with classpath [(memory)] and parent being scala.tools.nsc.util.ScalaClassLoader$URLClassLoader@59d12b6a 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))