jbrown
jbrown

Reputation: 7996

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

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?

Upvotes: 14

Views: 15350

Answers (2)

Rich Henry
Rich Henry

Reputation: 1849

You could also use the 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))
  }
}

Upvotes: 0

Kamil Domański
Kamil Domański

Reputation: 323

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))
}

Upvotes: 18

Related Questions