java 如何将 ENUM 绑定到单选按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3478177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to bind ENUM to radiobutton?
提问by Alexander
Typeis enum property in object.
类型是对象中的枚举属性。
jsp:
jsp:
<form:radiobutton path="type" value="Male" />
java:
爪哇:
public enum TestType
{
Male, Female;
}
and got error
并得到错误
Unable to convert value 'Male' from type 'java.lang.String' to type 'java.lang.Enum'; reason = 'java.lang.Enum is not an enum type'
无法将值 'Male' 从类型 'java.lang.String' 转换为类型 'java.lang.Enum';reason = 'java.lang.Enum 不是枚举类型'
回答by hrabinowitz
A simpler solution can be found at spring forum, without the need for any custom bindings.
一个更简单的解决方案可以在spring forum找到,不需要任何自定义绑定。
回答by Arthur Ronald
Do as follows
执行以下操作
public enum TestType {
MAN("Man"),
FEMALE("Female");
private String description;
private TestType(String description) {
this.description = description;
}
public String getValue() {
return name();
}
public void setValue(String value) {}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
And register a custom binder as follows
并注册一个自定义的活页夹如下
dataBinder.registerCustomEditor(TestType.class, new PropertyEditorSupport() {
@Override
public void setAsText(String value) throws IllegalArgumentException {
if(StringUtils.isBlank(value))
return;
setValue(TestType.valueOf(value));
}
@Override
public String getAsText() {
if(getValue() == null)
return "";
return ((TestType) getValue()).name();
}
});
Then
然后
<form:radiobuttons path="type" items="${testTypeList}" itemLabel="description"/>
You set up your TestType as follows
您按如下方式设置您的 TestType
model.addAttribute(TestType.values());
回答by axtavt
Perhaps, the typeproperty of the command object is decalred as Enuminstead of TestType?
也许,type命令对象的属性被标记为Enum而不是TestType?

