在我的 grails 应用程序中,我有这个枚举:
public enum RelationshipStatus{
Single_Never_Married,
Separated,
Divorced,
Widowed;
}
class MyCommand {
List<RelationshipStatus> relationshipStatuses
}
def myAction = {MyCommand myCommand ->
}
user.relationshipStatuses=Separated&user.relationshipStatuses=Divorced
myCommand.relationshipStatuses
将包含 RelationshipStatus.Separated
和 RelationshipStatus.Divorced
,但实际上它是空的。class RelationshipStatusEnumEditor extends PropertyEditorSupport {
public String getAsText() {
value.name()
}
public void setAsText(String text) {
RelationshipStatus.valueOf(text)
}
}
最佳答案
使用 Grails 2.3 中引入的数据绑定(bind)器,我想出了以下将请求参数转换为枚举集合的解决方案。例如,给定这些枚举
enum Gender {
MALE, FEMALE
}
enum Season {
SPRING, SUMMER, AUTUMN, WINTER
}
class MyCommand {
Collection<Gender> genders
Collection<Season> seasons
}
"MALE,FEMALE"
这样的字符串和 "SPRING,SUMMER,WINTER"
到相应的枚举集合。首先,提供 FormattedValueConverter
的实现进行转换class EnumCollectionConverter implements FormattedValueConverter {
/**
* To make other enums bindable, just add them to this list
*/
private static final List<Class<Enum>> convertableEnums = [Gender, Season]
@Override
Object convert(value, String format) {
Class<Enum> targetEnumClass = convertableEnums.find { it.simpleName == format }
if (targetEnumClass) {
List<String> enumConstantNames = value.toString().tokenize(',')
return enumConstantNames.collect { targetEnumClass.valueOf(it) }
}
value
}
@Override
Class<?> getTargetType() {
// this class converts to a Collection<T extends Enum<T>> but the return value
// of this method can't be any more specific than Collection due to type erasure
Collection
}
}
EnumCollectionConverter
作为 resources.groovy
中的 Spring bean - 为 bean 选择什么名称并不重要。然后要使用上面的类将逗号分隔的字符串转换为 num 集合,请使用注释相关属性class MyCommand {
@BindingFormat('Gender')
Collection<Gender> genders
@BindingFormat('Season')
Collection<Season> seasons
}
@BindingFormat
的值应该是将存储在绑定(bind)集合中的枚举类型的简单名称。
https://stackoverflow.com/questions/7216297/