【问题标题】:Getting case object instances which derive from a sealed parent in Scala获取从 Scala 中的密封父级派生的案例对象实例
【发布时间】:2015-08-29 05:06:53
【问题描述】:

This 本质上是我的问题,但接受的答案停止返回它们的符号而不是 case 对象本身。

理论上,这应该很容易:

def getCaseObjects(enumType: Type) = {
    val m = ru.runtimeMirror(getClass.getClassLoader)
    enumType.typeSymbol.asClass.knownDirectSubclasses map { subclass =>
        val enumObjMirror = m.reflectClass(subclass.asClass.toType.typeSymbol.asClass)
        enumObjMirror.reflectConstructor(subclass.asClass.toType.decl(ru.termNames.CONSTRUCTOR).asMethod)()
    }
}

这行得通!

...除了与 Parent 密封特征中包含的实例相比,它们是全新的实例;万岁,我已经打破了“案例对象是单身”的假设!

我可以在我的 Parent 密封特征中覆盖 equalshashCode 并完成它,但我更喜欢一种方法来获取 那些特定的 case 对象而不是那些碰巧看起来像他们。这可能吗?如果这有什么不同的话,我在 2.11。

【问题讨论】:

    标签: scala


    【解决方案1】:

    假设你在你引用的帖子中使用sealedDescendants方法,相信你应该可以得到底层的objects,比如:

    import scala.reflect.runtime.universe._
    import scala.reflect.runtime.{ universe => ru }
    val m = ru.runtimeMirror(getClass.getClassLoader)
    
    val descendants = sealedDescendants[Parent] getOrElse Set.empty
    
    val objects = descendants.map({ desc =>
      val mod = m.staticModule(desc.asClass.name.decoded)
      m.reflectModule(mod).instance
    })
    

    【讨论】:

    • 看准了!非常感谢。
    猜你喜欢
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2019-09-24
    • 2011-02-03
    • 1970-01-01
    相关资源
    最近更新 更多