How To Access access Case class field Value from String name of the field

Viewed 9769

How should I extract the value of a field of a case class from a given String value representing the field.

For example:

case class Person(name: String, age: Int)
val a = Person("test",10)

Now here given a string name or age i want to extract the value from variable a. How do i do this? I know this can be done using reflection but I am not exactly sure how?

3 Answers

I think it can do by convert case class to Map, then get field by name

def ccToMap(cc: AnyRef) =
  (Map[String, Any]() /: cc.getClass.getDeclaredFields) {
     (a, f) =>
     f.setAccessible(true)
     a + (f.getName -> f.get(cc))
}

Usage

case class Person(name: String, age: Int)

val column = Person("me", 16)
println(ccToMap(column))
val name = ccToMap(column)["name"]
Related