如何在 Scala 中反映 Enumeration class?

How to reflect Enumeration class in scala?

我有一个 Scala 枚举,我想从 String 中获取枚举值。

object CVVStatus extends Enumeration {
  type CVVStatus = Value
  val PRESENT, NOT_PRESENT, VALID, INVALID = Value
}

我想做这样的事情:

val prop = new Properties()
prop.load(new FileInputStream("config.conf"))
val tmp = prop.getProperty(propname)
val s:CVVStatus = StringtoEmum(tmp)

如果我需要从不同的枚举对象名到枚举对象的大量枚举,我应该如何实现?我应该导入什么包?

正如@Alec 在评论中指出的那样,这是 'for free' 和 Enumeration class,在工作表中很容易看到:

object CVVStatus extends Enumeration {
  type CVVStatus = Value
  val PRESENT, NOT_PRESENT, VALID, INVALID = Value
}

val test_present = "PRESENT"  // test_present: String = PRESENT
val test_incorrect = "INCORRECT"  // test_incorrect: String = INCORRECT
val enumeration_present = CVVStatus.withName(test_present)  // enumeration_present: CVVStatus.Value = PRESENT
val enumeration_incorrect = CVVStatus.withName(test_incorrect)  //java.util.NoSuchElementException: No value found for 'INCORRECT'

最后一个失败,因为它不是有效的枚举。 withName 文档内容如下:

Return a Value from this Enumeration whose name matches the argument s. The names are determined automatically via reflection.

无需进口。

您也可以考虑使用案例对象。作为参考,请查看这些 Whosebug 答案 Case Objects vs Enumerations How to access objects within an object by mixing in a trait with reflection?