[英]getting int value from enum in java
I have enum 我有枚举
enum Number{
FIRST(123),
SECOND(321);
}
Number nr=Number.FIRST
How can I get an enum value (not a String but int ) from my variable nr without creating a new method? 如何在不创建新方法的情况下从变量nr获取枚举值(不是String而是int)?
In Java, enums are objects too. 在Java中,枚举也是对象。 Provide a constructor for your numbers to be passed in, plus a public instance variable;
提供要传递的数字的构造函数,以及一个公共实例变量; no getter method necessary.
不需要吸气剂方法。
enum Num{
FIRST(123),
SECOND(321);
public final int value;
private Num(int value) { this.value = value; }
}
TL;DR: You can't. TL; DR:您不能。
Long version: 长版:
The code snippet you have above will not compile because you are missing the constructor: 您上面的代码片段将无法编译,因为您缺少构造函数:
private int value;
public Number(int i) {
this.value = i;
}
After you've done that, then you will need to provide the getter for value
: 完成此操作后,您将需要提供获取
value
:
public int getValue() {
return this.value;
}
EDIT: If you really, really, don't want to create a new method, you can make the value
field public
, but you're violating the OO concept of encapsulation (ie, best practice). 编辑:如果您确实真的不想创建新方法,则可以将
value
字段设为public
,但是您违反了OO封装的概念(即最佳实践)。
You need to write your enum like this (also, do not call it Number
please! There is java.lang.Number
): 您需要这样编写枚举(也请不要将其命名为
Number
!有java.lang.Number
):
enum MyNumber
{
FIRST(123),
SECOND(321);
private final int number;
MyNumber(final int number)
{
this.number = number;
}
public int getNumber()
{
return number;
}
}
If you don't want an accessor, remove the getter and make number
public. 如果你不想要的访问,删除getter和做出
number
公开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.