将字符串转换为枚举?
您好,我在尝试概括我为特定枚举编写的函数时遇到了麻烦:
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 函数。
提前致谢。
Hi I'm having trouble trying to generalize a function I've written for an specific enum:
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;
}
}
I wish to add a new parameter to the function that will represent any enum. I know I'm supposed to use templates but I can't use the function "values()" then inside the function code.
Basicly what I want is a valueOf function that uses the toString() value I've defined.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一种更简洁的方式来编写枚举:
这也解决了您的 String -> 问题枚举。仅使用三个字母的首字母缩略词作为枚举名称可能会更清晰,但如果您需要根据其他参数做出
getValue()
决定,这是正确的方法。Try a much cleaner way of writing your enum:
This also solves your problem of String -> Enum. It might be cleaner to just use the three-letter acronyms as the enum name, but in the case you will need to make the
getValue()
decision according to other parameters, this is the right way to go.我相信枚举可以实现接口,因此您可以使用 value() 方法定义一个接口,然后将其用作参数类型。
但正如评论者所说,如果您将枚举命名为 MKP、VOL 等,可能会更容易
I believe that Enums can implement interfaces, so you could define one with a values() method and then use that as your parameter type.
But as the commenter said, it would probably be easier if you named your enums MKP, VOL etc