1 16 package org.springframework.binding.format.support; 17 18 import org.springframework.binding.format.InvalidFormatException; 19 import org.springframework.core.enums.LabeledEnum; 20 import org.springframework.core.enums.LabeledEnumResolver; 21 import org.springframework.core.enums.StaticLabeledEnumResolver; 22 import org.springframework.util.Assert; 23 24 28 public class LabeledEnumFormatter extends AbstractFormatter { 29 30 private LabeledEnumResolver labeledEnumResolver = StaticLabeledEnumResolver.instance(); 31 32 public LabeledEnumFormatter() { 33 } 34 35 public LabeledEnumFormatter(boolean allowEmpty) { 36 super(allowEmpty); 37 } 38 39 public void setLabeledEnumResolver(LabeledEnumResolver labeledEnumResolver) { 40 Assert.notNull(labeledEnumResolver, "The labeled enum resolver is required"); 41 this.labeledEnumResolver = labeledEnumResolver; 42 } 43 44 protected String doFormatValue(Object value) { 45 LabeledEnum labeledEnum = (LabeledEnum)value; 46 return labeledEnum.getLabel(); 47 } 48 49 protected Object doParseValue(String formattedString, Class targetClass) throws IllegalArgumentException { 50 LabeledEnum labeledEnum = labeledEnumResolver.getLabeledEnumByLabel(targetClass, formattedString); 51 if (!isAllowEmpty()) { 52 Assert.notNull(labeledEnum, "The label '" + formattedString 53 + "' did not map to a valid enum instance for type " + targetClass); 54 Assert.isInstanceOf(targetClass, labeledEnum); 55 } 56 return labeledEnum; 57 } 58 59 public LabeledEnum parseLabeledEnum(String formattedString, Class enumClass) throws InvalidFormatException { 60 return (LabeledEnum)parseValue(formattedString, enumClass); 61 } 62 } | Popular Tags |