1 16 17 package org.springframework.beans.propertyeditors; 18 19 import java.beans.PropertyEditorSupport ; 20 import java.text.NumberFormat ; 21 22 import org.springframework.util.NumberUtils; 23 import org.springframework.util.StringUtils; 24 25 47 public class CustomNumberEditor extends PropertyEditorSupport { 48 49 private final Class numberClass; 50 51 private final NumberFormat numberFormat; 52 53 private final boolean allowEmpty; 54 55 56 70 public CustomNumberEditor(Class numberClass, boolean allowEmpty) throws IllegalArgumentException { 71 this(numberClass, null, allowEmpty); 72 } 73 74 88 public CustomNumberEditor(Class numberClass, NumberFormat numberFormat, boolean allowEmpty) 89 throws IllegalArgumentException { 90 91 if (numberClass == null || !Number .class.isAssignableFrom(numberClass)) { 92 throw new IllegalArgumentException ("Property class must be a subclass of Number"); 93 } 94 this.numberClass = numberClass; 95 this.numberFormat = numberFormat; 96 this.allowEmpty = allowEmpty; 97 } 98 99 100 103 public void setAsText(String text) throws IllegalArgumentException { 104 if (this.allowEmpty && !StringUtils.hasText(text)) { 105 setValue(null); 107 } 108 else if (this.numberFormat != null) { 109 setValue(NumberUtils.parseNumber(text, this.numberClass, this.numberFormat)); 111 } 112 else { 113 setValue(NumberUtils.parseNumber(text, this.numberClass)); 115 } 116 } 117 118 121 public void setValue(Object value) { 122 if (value instanceof Number ) { 123 super.setValue(NumberUtils.convertNumberToTargetClass((Number ) value, this.numberClass)); 124 } 125 else { 126 super.setValue(value); 127 } 128 } 129 130 133 public String getAsText() { 134 Object value = getValue(); 135 if (value == null) { 136 return ""; 137 } 138 if (this.numberFormat != null) { 139 return this.numberFormat.format(value); 141 } 142 else { 143 return value.toString(); 145 } 146 } 147 148 } 149 | Popular Tags |