注意:这个问题不是我如何在Scala中使用反射获得所有对象值和子对象值的重复?
这个问题的答案只适用于final成员。
例如:
scala> object Settings {
| val Host = "host"
| }
defined module Settings
deepMembers(Settings)
res0: Map[String,String] = Map()
一定是重复的,但我需要复习一下:
$ 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)
val members = Settings.getClass.getDeclaredFields.map(_.getName).filterNot(_ == "MODULE$")
members: Array[String] = Array(Host)
这是有效的,但我认为肯定有更好的方法。