1
2
3
4
5
6
7
8
9
10
11 package org.csveed.bean.conversion;
12
13 import static org.csveed.bean.conversion.ConversionUtil.hasText;
14
15 import java.text.NumberFormat;
16
17
18
19
20 public class CustomNumberConverter extends AbstractConverter<Number> {
21
22
23 private final Class<? extends Number> numberClass;
24
25
26 private final NumberFormat numberFormat;
27
28
29 private final boolean allowEmpty;
30
31
32
33
34
35
36
37
38
39
40
41
42 public CustomNumberConverter(Class<? extends Number> numberClass, boolean allowEmpty)
43 throws IllegalArgumentException {
44 this(numberClass, null, allowEmpty);
45 }
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60 public CustomNumberConverter(Class<? extends Number> numberClass, NumberFormat numberFormat, boolean allowEmpty)
61 throws IllegalArgumentException {
62 super(Number.class);
63
64 if (numberClass == null || !Number.class.isAssignableFrom(numberClass)) {
65 throw new IllegalArgumentException("Property class must be a subclass of Number");
66 }
67 this.numberClass = numberClass;
68 this.numberFormat = numberFormat;
69 this.allowEmpty = allowEmpty;
70 }
71
72 @Override
73 public Number fromString(String text) throws Exception {
74 if (this.allowEmpty && !hasText(text)) {
75 return null;
76 }
77 if (this.numberFormat != null) {
78 return determineValue(NumberUtils.parseNumber(text, this.numberClass, this.numberFormat));
79 }
80 return determineValue(NumberUtils.parseNumber(text, this.numberClass));
81 }
82
83
84
85
86
87
88
89
90
91 public Number determineValue(Object value) {
92 if (value instanceof Number) {
93 return NumberUtils.convertNumberToTargetClass((Number) value, this.numberClass);
94 }
95 return null;
96 }
97
98 @Override
99 public String toString(Number value) throws Exception {
100 if (value == null) {
101 return "";
102 }
103 if (this.numberFormat != null) {
104 return this.numberFormat.format(value);
105 }
106 return value.toString();
107 }
108
109 }