如何在Scala 2.10.x中按名称动态查找对象属性的值?
E.g。鉴于课程(它不能成为案例类):
class Row(val click: Boolean,
val date: String,
val time: String)
我想做类似的事情:
val fields = List("click", "date", "time")
val row = new Row(click=true, date="2015-01-01", time="12:00:00")
fields.foreach(f => println(row.getProperty(f))) // how to do this?
答案 0 :(得分:16)
class Row(val click: Boolean,
val date: String,
val time: String)
val row = new Row(click=true, date="2015-01-01", time="12:00:00")
row.getClass.getDeclaredFields foreach { f =>
f.setAccessible(true)
println(f.getName)
println(f.get(row))
}
答案 1 :(得分:0)
您还可以使用java / scala中的bean功能:
import scala.beans.BeanProperty
import java.beans.Introspector
object BeanEx extends App {
case class Stuff(@BeanProperty val i: Int, @BeanProperty val j: String)
val info = Introspector.getBeanInfo(classOf[Stuff])
val instance = Stuff(10, "Hello")
info.getPropertyDescriptors.map { p =>
println(p.getReadMethod.invoke(instance))
}
}