嗨,我在尝试概括我为特定枚举编写的函数时遇到了麻烦:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望在函数中添加一个新参数来表示任何枚举.我知道我应该使用模板但是我不能在函数代码中使用函数"values()".基本上我想要的是一个valueOf函数,它使用我定义的toString()值.
提前致谢.
Yuv*_*dam 16
尝试更清晰地编写枚举:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这也解决了你的String - > Enum的问题.使用三个字母的首字母缩略词作为枚举名称可能更简洁,但是如果您需要getValue()
根据其他参数做出决定,这是正确的方法.
归档时间: |
|
查看次数: |
1703 次 |
最近记录: |