My Grails应用程序有大量枚举,如下所示:
public enum Rating {
BEST("be"), GOOD("go"), AVERAGE("av"), BAD("ba"), WORST("wo")
final String id
private RateType(String id) {
this.id = id
}
static public RateType getEnumFromId(String value) {
values().find {it.id == value }
}
}
如果我有一个这样的命令对象:
class MyCommand {
Rating rating
}
我想(例如)自动将值为“wo”的请求参数转换为Rating.WORST。
定义自定义转换器的过程描述为here(在将字符串转换为日期的上下文中)。虽然这个过程很好,但我不想为每个枚举创建一个实现PropertyEditorSupport的类。还有更好的选择吗?
答案 0 :(得分:12)
我找到了一个我很满意的解决方案。
步骤1:创建PropertyEditorSupport的实现,以将文本转换为相关枚举的文本
public class EnumEditor extends PropertyEditorSupport {
private Class<? extends Enum<?>> clazz
public EnumEditor(Class<? extends Enum<?>> clazz) {
this.clazz = clazz
}
public String getAsText() {
return value?.id
}
public void setAsText(String text) {
value = clazz.getEnumFromId(text)
}
}
步骤2:定义一个类,它将EnumEditor注册为各种枚举类的转换器。要更改可通过id绑定的枚举类列表,只需修改BINDABLE_ENUMS
public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
private static final String REQUIRED_METHOD_NAME = 'getEnumFromId'
// Add any enums that you want to bind to by ID into this list
private static final BINDABLE_ENUMS = [Rating, SomeOtherEnum, SomeOtherEnum2]
public void registerCustomEditors(PropertyEditorRegistry registry) {
BINDABLE_ENUMS.each {enumClass ->
registerEnum(registry, enumClass)
}
}
/**
* Register an enum to be bound by ID from a request parameter
* @param registry Registry of types eligible for data binding
* @param enumClass Class of the enum
*/
private registerEnum(PropertyEditorRegistry registry, Class<? extends Enum<?>> enumClass) {
boolean hasRequiredMethod = enumClass.metaClass.methods.any {MetaMethod method ->
method.isStatic() && method.name == REQUIRED_METHOD_NAME && method.parameterTypes.size() == 1
}
if (!hasRequiredMethod) {
throw new MissingMethodException(REQUIRED_METHOD_NAME, enumClass, [String].toArray())
}
registry.registerCustomEditor(enumClass, new EnumEditor(enumClass))
}
}
第3步:通过在grails-app/conf/spring/resources.grooovy
customPropertyEditorRegistrar(CustomPropertyEditorRegistrar)
答案 1 :(得分:11)
因此,默认数据绑定绑定Enum名称,而不是Enum的单独定义属性。你可以像你提到的那样create your own PropertyEditor或者做类似的解决方法:
class MyCommand {
String ratingId
Rating getRating() {
return Rating.getEnumFromId(this.ratingId)
}
static constraints = {
ratingId(validator:{val, obj -> Rating.getEnumFromId(val) != null })
}
}