Scala reflection to access all public fields at runtime

scala

Solution

In brief:

import scala.reflect.runtime.universe._

val a = new A
val rm = scala.reflect.runtime.currentMirror
val accessors = rm.classSymbol(a.getClass).toType.members.collect {
  case m: MethodSymbol if m.isGetter && m.isPublic => m 
}
val instanceMirror = rm.reflect(a)
for(acc <- accessors)
  println(s"$a: ${instanceMirror.reflectMethod(acc).apply()}")

Problem

Given the following class hierarchy: ``` class A { val x = 3 val y = 4 } class B extends A { val z = 5 } ``` And say I have an instance of B with no compile-time knowledge of its class hierarchy and would like to be able to report something like the following: ``` Class: B val[x]: 3 val[y]: 4 val[z]: 5 ``` What would be the best approach using Scala reflection? Thanks Des

Original source