1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.beanutils.converters;
19
20
21 import java.math.BigDecimal;
22 import org.apache.commons.beanutils.ConversionException;
23 import org.apache.commons.beanutils.Converter;
24
25
26 /**
27 * <p>Standard {@link Converter} implementation that converts an incoming
28 * String into a <code>java.math.BigDecimal</code> object, optionally using a
29 * default value or throwing a {@link ConversionException} if a conversion
30 * error occurs.</p>
31 *
32 * @author Craig R. McClanahan
33 * @version $Revision: 1.7 $ $Date: 2004/02/28 13:18:34 $
34 * @since 1.3
35 */
36
37 public final class BigDecimalConverter implements Converter {
38
39
40
41
42
43 /**
44 * Create a {@link Converter} that will throw a {@link ConversionException}
45 * if a conversion error occurs.
46 */
47 public BigDecimalConverter() {
48
49 this.defaultValue = null;
50 this.useDefault = false;
51
52 }
53
54
55 /**
56 * Create a {@link Converter} that will return the specified default value
57 * if a conversion error occurs.
58 *
59 * @param defaultValue The default value to be returned
60 */
61 public BigDecimalConverter(Object defaultValue) {
62
63 this.defaultValue = defaultValue;
64 this.useDefault = true;
65
66 }
67
68
69
70
71
72 /**
73 * The default value specified to our Constructor, if any.
74 */
75 private Object defaultValue = null;
76
77
78 /**
79 * Should we return the default value on conversion errors?
80 */
81 private boolean useDefault = true;
82
83
84
85
86
87 /**
88 * Convert the specified input object into an output object of the
89 * specified type.
90 *
91 * @param type Data type to which this value should be converted
92 * @param value The input value to be converted
93 *
94 * @exception ConversionException if conversion cannot be performed
95 * successfully
96 */
97 public Object convert(Class type, Object value) {
98
99 if (value == null) {
100 if (useDefault) {
101 return (defaultValue);
102 } else {
103 throw new ConversionException("No value specified");
104 }
105 }
106
107 if (value instanceof BigDecimal) {
108 return (value);
109 }
110
111 try {
112 return (new BigDecimal(value.toString()));
113 } catch (Exception e) {
114 if (useDefault) {
115 return (defaultValue);
116 } else {
117 throw new ConversionException(e);
118 }
119 }
120
121 }
122
123
124 }