如何获取枚举值的枚举定义?
object TestEnum extends Enumeration{
val One = Value("One")
val Two,Three= Value
}
println(TestEnum.One.getClass)
println(TestEnum.One.getClass.getDeclaringClass)//get Enumeration
所以我的问题是如何从 TestEnum.One 获取 Class[TestEnum] ?
谢谢。
object TestEnum extends Enumeration{
val One = Value("One")
val Two,Three= Value
}
println(TestEnum.One.getClass)
println(TestEnum.One.getClass.getDeclaringClass)//get Enumeration
So my question is how to get Class[TestEnum] from TestEnum.One?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不幸的是,我认为你不能。
TestEnum.One
实际上只是Enumeration#Value
类的一个实例。事实上,这比这更糟糕 - 你的枚举值都按类型被删除为同一件事:由于枚举的实例只是
Enumeration#Value
的实例,因此它们的声明类只是 <代码>scala.Enumeration。这很令人沮丧,但这些 scala 枚举似乎比无用更糟糕;如果你通过序列化传递它们(至少在 2.7.7 中),那么你也不能进行相等检查!
I don't think you can unfortunately.
TestEnum.One
is really just an instance of the classEnumeration#Value
. In fact, it's lots worse than just this - your enumeration values are all erased by type to the same thing:As the instances of your enumeration are just instances of
Enumeration#Value
, their declaring class is justscala.Enumeration
.It's frustrating but it seems like these scala enums are worse than useless; if you pass them through serialization (at least in 2.7.7), then you can't do equality checks either!
由于您提到的限制,我将发布一个指向我编写的枚举类型的链接。我不使用内置枚举类型,因为我发现它非常有限。尽管它没有您想要的功能(从元素获取枚举),但添加它会非常简单。如果您发现它有帮助,请随意以任何方式使用它。
(来源和测试/示例):
http://gist.github.com/282446
顺便说一句,如果您喜欢并需要帮助将容器添加到EnumElement 让我知道。
I am going to post a link to the Enum type that I wrote due to the limitations you mentioned. I don't use the built in enumeration type as I find it very limiting. Though it doesn't have the feature you would like (get the Enumeration from an Element), it would be pretty trivial to add it. Feel free to use it in any way if you find it helpful.
(source & test / example):
http://gist.github.com/282446
BTW If you like and want help adding the container to the EnumElement let me know.
在我看来,有一个简单的解决方案可以不处理 Scala 枚举:使用 Java enum-s 代替。 Scala 已经支持交叉编译一段时间了,只需在 Scala 源文件夹中添加 Java 枚举即可轻松完成。
In my opinion there is a simple solution for not dealing with Scala Enumerations: use Java enum-s instead. Scala has supported cross-compiling for a while now and it's easy to just add a Java enum in your Scala source folder.