gpt4 book ai didi

scala - 如何在 Scala 中使用反射获取所有(非最终)对象 val 和子对象 val?

转载 作者:行者123 更新时间:2023-12-04 13:48:26 24 4
gpt4 key购买 nike

注意:此问题不是 How can I get all object vals and subobject vals using reflection in Scala? 的重复问题

该问题中提供的答案仅适用于最终成员。

例如:

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)

关于scala - 如何在 Scala 中使用反射获取所有(非最终)对象 val 和子对象 val?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31324664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com