您好,我在尝试概括我为特定枚举编写的函数时遇到了麻烦:
public static enum InstrumentType {
SPOT {
public String toString() {
return "MKP";
}
},
VOLATILITY {
public String toString() {
return "VOL";
}
};
public static InstrumentType parseXML(String value) {
InstrumentType ret = InstrumentType.SPOT;
for(InstrumentType instrumentType : values()) {
if(instrumentType.toString().equalsIgnoreCase(value)) {
ret = instrumentType;
break;
}
}
return ret;
}
}
我希望向代表任何枚举的函数添加一个新参数。我知道我应该使用模板,但我不能在函数代码中使用函数“values()”。 基本上我想要的是一个使用我定义的 toString() 值的 valueOf 函数。
提前致谢。
最佳答案
尝试一种更简洁的方式来编写枚举:
public static enum InstrumentType {
SPOT("MKP"),
VOLATILITY("VOL");
private final String name;
InstrumentType(String name)
{
this.name = name;
}
public String toString()
{
return this.name;
}
public static InstrumentType getValue(String s)
{
for (InstrumentType t : InstrumentType.values())
{
if (t.toString().equals(s))
return t;
}
return SOME_DEFAULT_VALUE;
}
}
这也解决了您的 String -> Enum 问题。仅使用三个字母的首字母缩略词作为枚举名称可能会更清晰,但如果您需要根据其他参数做出 getValue()
决定,这是正确的方法.
关于java - 将字符串转换为枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1818712/