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

How can I dynamically search for an object property value by name in Scala 2.10.x?

eg. Given the class (this cannot be the 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? 
+7
scala
source share
2 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)) } 
+12
source share

You can also use bean functionality from java / scala:

 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)) } } 
0
source share

All Articles