View Javadoc
1   package org.csveed.bean.conversion;
2   
3   import static org.csveed.bean.conversion.ConversionUtil.hasText;
4   
5   import java.text.NumberFormat;
6   
7   public class CustomNumberConverter extends AbstractConverter<Number> {
8   
9       private final Class<? extends Number> numberClass;
10  
11      private final NumberFormat numberFormat;
12  
13      private final boolean allowEmpty;
14  
15      public CustomNumberConverter(Class<? extends Number> numberClass, boolean allowEmpty) throws IllegalArgumentException {
16          this(numberClass, null, allowEmpty);
17      }
18  
19      public CustomNumberConverter(Class<? extends Number> numberClass,
20                                NumberFormat numberFormat, boolean allowEmpty) throws IllegalArgumentException {
21          super(Number.class);
22  
23          if (numberClass == null || !Number.class.isAssignableFrom(numberClass)) {
24              throw new IllegalArgumentException("Property class must be a subclass of Number");
25          }
26          this.numberClass = numberClass;
27          this.numberFormat = numberFormat;
28          this.allowEmpty = allowEmpty;
29      }
30  
31      @Override
32      public Number fromString(String text) throws Exception {
33          if (this.allowEmpty && !hasText(text)) {
34              return null;
35          } else if (this.numberFormat != null) {
36              return determineValue(NumberUtils.parseNumber(text, this.numberClass, this.numberFormat));
37          } else {
38              return determineValue(NumberUtils.parseNumber(text, this.numberClass));
39          }
40      }
41  
42      public Number determineValue(Object value) {
43          if (value instanceof Number) {
44              return NumberUtils.convertNumberToTargetClass((Number) value, this.numberClass);
45          }
46          return null;
47      }
48  
49      @Override
50      public String toString(Number value) throws Exception {
51          if (value == null) {
52              return "";
53          }
54          if (this.numberFormat != null) {
55              return this.numberFormat.format(value);
56          }
57          return value.toString();
58      }
59  
60  }