[英]enum getter returning wrong value
I have an enum Type 我有一个枚举类型
public enum Type {
A("abc1", "desc1"),
B("abc2", "desc2"),
C("abc3", "desc3"),
D("abc4", "desc4"),
E("abc5", "desc5");
private String value;
private String description;
private Type(String value, String description) {
this.value = value;
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
I get the values from the enum through the following code 我通过以下代码从枚举中获取值
Type[] type = Type.values();
for (int i = 0; i < type.length; i++) {
System.out.println(type[i].getValue());
}
This code runs on a server. 此代码在服务器上运行。 For few days it runs fine and the output of this code is as follows :
几天来,它运行良好,此代码的输出如下:
abc1
abc2
abc3
abc4
abc5
But after few days the output changes to 但是几天后,输出更改为
abc1
abc2
abc1
abc4
abc5
If I print the description then they are always correct. 如果我打印说明,那么它们总是正确的。
I am not able to figure out why Type.getValue() is returning value of enum Value A for enum Value C. 我无法弄清楚为什么Type.getValue()返回枚举值C的枚举值A的值。
Your enum is mutable; 您的枚举是可变的; something is calling
setValue()
. 有些东西正在调用
setValue()
。
You should make your enum immutable - it makes good sense to do this. 您应该使您的枚举不可变 -这样做很有意义。 Make it immutable by making the fields final and ditching the setters:
通过将字段定为最终值并放弃二传手来使其不可变:
public enum Type {
A("abc1", "desc1"),
B("abc2", "desc2"),
C("abc3", "desc3"),
D("abc4", "desc4"),
E("abc5", "desc5");
private final String value;
private final String description;
private Type(String value, String description) {
this.value = value;
this.description = description;
}
public String getDescription() {
return description;
}
public String getValue() {
return value;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.