希望能够检索案例类的参数名称和类型。我能够获得名字,但不能获得名称和类型。这是我的一次尝试,它基于Stackoverflow上的其他片段。注释掉的部分是我想做但不起作用的部分。
def getMethods[T: TypeTag] = typeOf[T].members.collect {
//case m: MethodSymbol if m.isCaseAccessor => (m, classOf[T].getDeclaredField(m).getType())
case m: MethodSymbol if m.isCaseAccessor => m
}.toList
case class Person(name: String, age: Int)
getMethods[Person]
删除评论并评论下面的行
<console>:13: error: class type required but T found
case m: MethodSymbol if m.isCaseAccessor => (m, classOf[T].getDeclaredField(m).getType())
我正在寻找像List(("name", String), ("age", Int))
或类似的东西。我想scala 2.10但scala 2.11也没关系。
答案 0 :(得分:1)
import scala.reflect.runtime.{universe => ru}
def getSymbols[T: ru.TypeTag]: List[ru.Symbol] = ru.typeOf[T].members.toList
case class Person(name: String, age: Int)
scala> getSymbols[Person].filter(!_.isMethod).map(x=>x.name->x.info)
res1: List[(reflect.runtime.universe.Symbol#NameType, reflect.runtime.universe.Type)] = List((age ,scala.Int), (name ,String))