如何从值转换为枚举?
我有一个看起来有点像这样的枚举:
public enum Numbers {
ONE(1), TWO(2), THREE(3);
public final int num;
public Numbers(int num) {
this.num = num;
}
}
我希望能够从参数转换为枚举,例如从 int 1
转换为枚举 ONE
。 Java Enums 中是否有任何内置机制可以做到这一点,或者我是否必须为此编写自己的逻辑?
I have an enum that looks a little bit like this:
public enum Numbers {
ONE(1), TWO(2), THREE(3);
public final int num;
public Numbers(int num) {
this.num = num;
}
}
I want to be able to convert from argument to enum, for instance from the int 1
to the enum ONE
. Is there any built-in mechanism in Java Enums to do this, or do I have to write my own logic for it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您必须编写自己的逻辑,因为 num 变量是您自己逻辑的一部分:
Yes you have to write your own logic as the
num
variable is a part of your own logic :如果你想从序数转换,你必须自己做。然而,枚举名称会自动转换。顺便说一句,不需要指定序数,这是自动完成的,它以 0 开头,并且有一个 ordinal() getter。
将返回 Numbers.ONE
If you want conversion from the ordinal you have to do it yourself. There is however automatic conversion from the name of an enum. Btw there is no need to specify the ordinal, that is done automatically and it starts with 0 and there is a ordinal() getter.
would return Numbers.ONE
如果您可以使用
ZERO
开始您的特定枚举,那么您可以执行并忽略为您的枚举分配索引。
编辑:重构安全选项:
这也有利于将索引更改为您喜欢的任何类型,并返回 null 而不是在您要求垃圾时抛出异常(这可能更好)。
If you can start your particular enum with
ZERO
instead, you could doand ignore assigning indices to your enum.
EDIT: refactor safe option:
this is also conducive to changing your index to whatever type you like and returns null instead of throwing an exception if you ask for garbage (which can be preferable).