Scala 2.10 反射,如何从案例类中提取字段值,即案例类中的字段列表 [英] Scala 2.10 reflection, how do I extract the field values from a case class, i.e. field list from case class

查看:64
本文介绍了Scala 2.10 反射,如何从案例类中提取字段值,即案例类中的字段列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 Scala 2.10 中的新反射模型从 Scala 中的案例类中提取字段值?例如,使用下面的不拉出字段方法

How can I extract the field values from a case class in scala using the new reflection model in scala 2.10? For example, using the below doesn't pull out the field methods

  def getMethods[T:TypeTag](t:T) =  typeOf[T].members.collect {
    case m:MethodSymbol => m
  }

我打算将它们泵入

  for {field <- fields} {
    currentMirror.reflect(caseClass).reflectField(field).get
  }

推荐答案

MethodSymbol 有一个 isCaseAccessor 方法可以让你精确地做到这一点:

MethodSymbol has an isCaseAccessor method that allows you to do precisely this:

def getMethods[T: TypeTag] = typeOf[T].members.collect {
  case m: MethodSymbol if m.isCaseAccessor => m
}.toList

现在您可以编写以下内容:

Now you can write the following:

scala> case class Person(name: String, age: Int)
defined class Person

scala> getMethods[Person]
res1: List[reflect.runtime.universe.MethodSymbol] = List(value age, value name)

而且你只会得到你想要的方法符号.

And you get only the method symbols you want.

如果您只想要实际的字段名称(而不是 value 前缀)并且您希望它们的顺序相同,那么:

If you just want the actual field name (not the value prefix) and you want them in the same order then:

def getMethods[T: TypeTag]: List[String] =
  typeOf[T].members.sorted.collect {
    case m: MethodSymbol if m.isCaseAccessor => m.name.toString
  }

这篇关于Scala 2.10 反射,如何从案例类中提取字段值,即案例类中的字段列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆