如何从 Java 枚举中获取值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35140408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get value from a Java enum
提问by Mandar
I have a enum which looks like:
我有一个枚举,它看起来像:
public enum Constants{
YES("y"), NO("N")
private String value;
Constants(String value){
this.value = value;
}
}
I have a test class which looks like
我有一个测试类,看起来像
public class TestConstants{
public static void main(String[] args){
System.out.println(Constants.YES.toString())
System.out.println(Constants.NO.toString())
}
}
The output is:
输出是:
YES
NO
instead of
代替
Y
N
I am not sure what is wrong here ??
我不确定这里有什么问题?
采纳答案by Mohammed Aouf Zouag
You need to overridethe toString
method of your enum:
您需要覆盖toString
枚举的方法:
public enum Constants{
YES("y"), NO("N")
// No changes
@Override
public String toString() {
return value;
}
}
回答by m.aibin
Write Getter and Setter for value
and use:
编写 Getter 和 Settervalue
并使用:
System.out.println(Constants.YES.getValue());
System.out.println(Constants.NO.getValue());
回答by David Yee
You can also add a getter to the enumeration and simply call on it to access the instance variable:
您还可以向枚举添加一个 getter 并简单地调用它来访问实例变量:
public enum Constants{
YES("Y"), NO("N");
private String value;
public String getResponse() {
return value;
}
Constants(String value){
this.value = value;
}
}
public class TestConstants{
public static void main(String[] args){
System.out.println(Constants.YES.getResponse());
System.out.println(Constants.NO.getResponse());
}
}
回答by Just a Logic Gate
Create a getValue() method in your enum, and use this instead of toString().
在枚举中创建一个 getValue() 方法,并使用它代替 toString()。
public enum Constants{
YES("y"), NO("N")
private String value;
Constants(String value){
this.value = value;
}
}
public String getValue(){
return value;
}
And instead of:
而不是:
System.out.println(Constants.YES.toString())
System.out.println(Constants.NO.toString())
(Which are also missing a semi-colon), use
(也缺少分号),使用
System.out.println(Constants.YES.getValue());
System.out.println(Constants.NO.getValue());
Hope this solved your problem. If you do not want to create a method in your enum, you can make your value field public, but this would break encapsulation.
希望这解决了您的问题。如果不想在枚举中创建方法,可以将值字段设为公开,但这会破坏封装。
回答by Peter Isberg
String enumValue = Constants.valueOf("YES")
Java doc ref: https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#valueOf(java.lang.Class,%20java.lang.String)
Java 文档参考:https://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#valueOf(java.lang.Class,% 20java.lang.String)