在Java枚举中覆盖valueof()和toString() [英] Override valueof() and toString() in Java enum
问题描述
我的枚举中的值
是需要在其中具有空格的单词,但枚举在其值中不能有空格,因此它们都已经被打了。我想覆盖 toString()
添加这些空格,我告诉它。
我也想要枚举当我在我添加空格的相同字符串上使用 valueOf()
时提供正确的枚举。
例如:
public enum RandomEnum
{
StartHere,
StopHere
调用 toString()
on RandomEnum
其值为 StartHere
返回字符串从这里开始
。在同一个字符串(从这里开始
)调用 valueof()
)返回枚举值 StartHere
。
我该怎么做?
你可以试试这个代码。由于您不能覆盖 valueOf
方法,您必须在下面的示例代码中定义自定义方法( getEnum
),返回您需要的价值,并更改您的客户端以使用此方法。
public enum RandomEnum {
StartHere(Start Here),
StopHere(Stop Here);
private String value;
RandomEnum(String value){
this.value = value;
}
public String getValue(){
返回值;
}
@Override
public String toString(){
return this.getValue();
}
public static RandomEnum getEnum(String value){
for(RandomEnum v:values())
if(v.getValue()。equalsIgnoreCase ))return v;
throw new IllegalArgumentException();
}
}
The values in my enum
are words that need to have spaces in them, but enums can't have spaces in their values so it's all bunched up. I want to override toString()
to add these spaces where I tell it to.
I also want the enum to provide the correct enum when I use valueOf()
on the same string that I added the spaces to.
For example:
public enum RandomEnum
{
StartHere,
StopHere
}
Call toString()
on RandomEnum
whose value is StartHere
returns string "Start Here"
. Call valueof()
on that same string ("Start Here"
) returns enum value StartHere
.
How can I do this?
You can try out this code. Since you cannot override valueOf
method you have to define a custom method (getEnum
in the sample code below) which returns the value that you need and change your client to use this method instead.
public enum RandomEnum {
StartHere("Start Here"),
StopHere("Stop Here");
private String value;
RandomEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return this.getValue();
}
public static RandomEnum getEnum(String value) {
for(RandomEnum v : values())
if(v.getValue().equalsIgnoreCase(value)) return v;
throw new IllegalArgumentException();
}
}
这篇关于在Java枚举中覆盖valueof()和toString()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!