Scala:动态获取对象的字段名称和值?

时间:2015-03-10 22:23:57

标签: scala

以下代码有效,但我希望将其改进为更通用。

trait Person{
  def name: String
  def age: Int
  val sex: String
  def listCustomFields:Unit = UtilClass(this)
}
case class Student(name: String, age: Int, sex:String) extends Person{
  // A custome field
  var school = "A"
}
case class Employee(name: String, age: Int, sex: String) extends Person{
  // Some custom fields
  var country:String = "Somewhere"
  val salary:Int = 123
}

case class UtilClass(claz:Person){
       claz match {
         case c:Student => println(s"Student with custom field ${c.school}")
           // Todo: How do I programatically list the custom fields without knowing their names ?
         case c:Employee => println(s"Employee with custom fields country: ${c.country}, salary: ${c.salary}")
       }
   // If only the following works
   //claz.getFields.map(f:Field => println(s"${f.getName} ${f.getValue}}"))

}
object GetArgumentValueByName extends App{

  val employee = new Employee("John", 32, "M")
  employee.country = "Earth"
  employee.listCustomFields
 // Output: Employee with custom fields country: Earth, salary: 123

}

我一直在关注reflect.runtime.universe,但仍然不明白该怎么做。本质上,它是在运行时获取字段及其值的列表。

1 个答案:

答案 0 :(得分:0)

你想要对这些字段做什么?如果您只想显示它们,请覆盖toString。如果你想能够用它们做些什么,unapply就是你想要的,虽然你有这种结构的方式是行不通的。如果不了解您的预期用途,我建议您这样做:

abstract class Person(name: String, age: Int, sex: String)
case class Student(name: String, age: Int, sex: String, school: String) extends Person(name, age, sex)
case class Employee(name: String, age: Int, sex: String, country: String, salary: Int) extends Person(name, age, sex)