Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: How to access a class property dynamically by name?

Tags:

scala

How can I look up the value of an object's property dynamically by name in Scala 2.10.x?

E.g. Given the class (it can't be a case class):

class Row(val click: Boolean,
          val date: String,
          val time: String)

I want to do something like:

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?
like image 701
jbrown Avatar asked Feb 11 '15 16:02

jbrown


1 Answers

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))
}
like image 56
Kamil Domański Avatar answered Oct 14 '22 20:10

Kamil Domański