mercredi 25 mars 2020

Scala Reflection - Get list of fields

I would like to start from :

case class Foo(a: Int, b: String, c: Seq[Int]) {
  val bar: Int = ???
  lazy val bar2 = ???
}

and being able to get a Map[String, Any] which would be :

Map(
  "a" -> foo.a,
  "b" -> foo.b,
  "c" -> foo.c

Extract the name and the value of all the fields of the given class.

I looked at clapper and tried:

ClassUtil
      .scalaAccessorMethods(this.getClass)
      .filter(ClassUtil.isGetter)
      .filter(!_.getName.contains("$"))
      .filter(_.getName != "Empty")
      .map { m =>
        (m.getName, m.invoke(this))
      }
      .filter { case (_, v) => Option(v).isDefined }

But this also return the values of the extra val and lazy val defined inside the case class.

Thank you.





Aucun commentaire:

Enregistrer un commentaire