我有一个看起来像这样的对象:
object Settings {
final val Host = "host"
final val Protocol = "protocol"
object User {
final val Name = "username"
final val Password = "password"
}
object Subject {
final val Query = "query"
final val Predicate = "predicate"
}
}
我想做的是类似于membersAsHash(classOf[CollectionSettings])
并接收我在对象中声明的所有 val 的哈希值:
[
Host => "host",
Protocol => "protocol",
Name => "username",
Password => "password",
Query => "query",
Predicate => "predicate"
]
如果密钥是一个字符串,甚至是完整的包名(例如 com.example.Settings.User),也可以。我真正需要的是价值观,所以如果我只能得到它,它仍然是可以接受的。
这让我得到了子对象的名称,但我似乎无法弄清楚如何获取每个内部的 val:
val optionsToCheck = {
import scala.reflect.runtime.{universe => ru}
val mirror = ru.runtimeMirror(getClass.getClassLoader)
val subObjects = ru.typeOf[CollectionSettings.type].declarations.filter(_.isModule)
subobjects.map(o => mirror.reflectModule(o.asModule).instance.asInstanceOf[Object].toString).toList
}