8

有以下枚举

object ResponseType extends Enumeration {
  val Listing, Album = Value
}

如何获取其 val 列表?

4

3 回答 3

16

如果您想彻底了解这一点,您需要检查您的符号是否Value具有超类型:

def valueSymbols[E <: Enumeration: TypeTag] = {
  val valueType = typeOf[E#Value]
  typeOf[E].members.filter(sym => !sym.isMethod &&
    sym.typeSignature.baseType(valueType.typeSymbol) =:= valueType
  )
}

现在,即使您有以下内容(这是完全合法的):

object ResponseType extends Enumeration {
  val Listing, Album = Value
  val someNonValueThing = "You don't want this in your list of value symbols!"
}

你仍然得到正确的答案:

scala> valueSymbols[ResponseType.type] foreach println
value Album
value Listing

您当前的方法将包括value someNonValueThing此处。

于 2012-08-26T20:58:51.967 回答
7

以下代码获取Symbol表示“vals”的对象列表:

import reflect.runtime.universe._ // Access the reflection api

typeOf[ResponseType.Value]  //  - A `Type`, the basic unit of reflection api
  .asInstanceOf[TypeRef]    //  - A specific kind of Type with knowledge of
                            //    the place it's being referred from
  .pre                      //  - AFAIK the referring Type
  .members                  //  - A list of `Symbol` objects representing
                            //    all members of this type, including 
                            //    private and inherited ones, classes and 
                            //    objects - everything.
                            //    `Symbol`s are the second basic unit of 
                            //    reflection api.
  .view                     //  - For lazy filtering
  .filter(_.isTerm)         //  - Leave only the symbols which extend the  
                            //    `TermSymbol` type. This is a very broad 
                            //    category of symbols, which besides values
                            //    includes methods, classes and even 
                            //    packages.
  .filterNot(_.isMethod)    //  - filter out the rest
  .filterNot(_.isModule)
  .filterNot(_.isClass)
  .toList                   //  - force the view into a final List

应该注意的是,它可以通过.collect对特定类型的测试来实现,而不是过滤 is 子句,如下所示:

.collect{ case symbol : MethodSymbol => symbol }

反射 api 中的其他任务可能需要这种方法。

还应该注意的是,使用 a.view根本不是强制性的,它只是filter通过mapflatMap遍历输入集合一次且在它实际上被强制进入一些具体集合的点(.toList在我们的例子中)。

更新

正如 Travis Brown 所建议的,也可以ResponseType直接引用该对象。所以该typeOf[ResponseType.Value].asInstanceOf[TypeRef].pre部分可以替换为 typeOf[ResponseType.type]

于 2012-08-26T09:54:48.240 回答
3

您可以通过枚举的 values 方法返回的集合迭代枚举的值:

scala> for (e <- ResponseType.values) println(e)
Listing
Album
于 2012-08-26T10:12:06.037 回答