How can I get all (non-final) object vals and subobject vals using reflection in Scala?
Asked Answered
A

2

3

Note: This question is not a duplicate of How can I get all object vals and subobject vals using reflection in Scala?

The answer provided in that question only works for final members.

For example:

scala> object Settings {
     |   val Host = "host"
     | }
defined module Settings

deepMembers(Settings)
res0: Map[String,String] = Map()
Ananthous answered 9/7, 2015 at 17:44 Comment(0)
T
4

It must be a duplicate, but I need a refresher:

$ scala
Welcome to Scala version 2.11.7 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_45).
Type in expressions to have them evaluated.
Type :help for more information.

scala> object Settings { val Host = "host" ; val Guest = "guest" }
defined object Settings

scala> import reflect.runtime._,universe._
import reflect.runtime._
import universe._

scala> val im = currentMirror reflect Settings
im: reflect.runtime.universe.InstanceMirror = instance mirror for Settings$@c8e4bb0

scala> im.symbol.asClass.typeSignature.members filter (s => s.isTerm && s.asTerm.isAccessor)
res0: Iterable[reflect.runtime.universe.Symbol] = SynchronizedOps(value Guest, value Host)

scala> res0 map (im reflectMethod _.asMethod) map (_.apply())
res2: Iterable[Any] = List(guest, host)
Thunderclap answered 9/7, 2015 at 18:37 Comment(0)
A
0
val members = Settings.getClass.getDeclaredFields.map(_.getName).filterNot(_ == "MODULE$")
members: Array[String] = Array(Host)

This works but I think there's certainly a better way of doing this.

Ananthous answered 9/7, 2015 at 18:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.