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.util.List;
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 primitive array of char. On a conversion failure, returns
29 * a specified default value or throws a {@link ConversionException} depending
30 * on how this instance is constructed.</p>
31 *
32 * @author Craig R. McClanahan
33 * @version $Revision: 1.7 $ $Date: 2004/02/28 13:18:34 $
34 * @since 1.4
35 */
36
37 public final class CharacterArrayConverter extends AbstractArrayConverter {
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 CharacterArrayConverter() {
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 CharacterArrayConverter(Object defaultValue) {
62
63 this.defaultValue = defaultValue;
64 this.useDefault = true;
65
66 }
67
68
69
70
71
72 /**
73 * <p>Model object for type comparisons.</p>
74 */
75 private static char model[] = new char[0];
76
77
78
79
80
81 /**
82 * Convert the specified input object into an output object of the
83 * specified type.
84 *
85 * @param type Data type to which this value should be converted
86 * @param value The input value to be converted
87 *
88 * @exception ConversionException if conversion cannot be performed
89 * successfully
90 */
91 public Object convert(Class type, Object value) {
92
93
94 if (value == null) {
95 if (useDefault) {
96 return (defaultValue);
97 } else {
98 throw new ConversionException("No value specified");
99 }
100 }
101
102
103 if (model.getClass() == value.getClass()) {
104 return (value);
105 }
106
107
108 if (strings.getClass() == value.getClass()) {
109 try {
110 String values[] = (String[]) value;
111 char results[] = new char[values.length];
112 for (int i = 0; i < values.length; i++) {
113 results[i] = values[i].charAt(0);
114 }
115 return (results);
116 } catch (Exception e) {
117 if (useDefault) {
118 return (defaultValue);
119 } else {
120 throw new ConversionException(value.toString(), e);
121 }
122 }
123 }
124
125
126
127 try {
128 List list = parseElements(value.toString());
129 char results[] = new char[list.size()];
130 for (int i = 0; i < results.length; i++) {
131 results[i] = ((String) list.get(i)).charAt(0);
132 }
133 return (results);
134 } catch (Exception e) {
135 if (useDefault) {
136 return (defaultValue);
137 } else {
138 throw new ConversionException(value.toString(), e);
139 }
140 }
141
142 }
143
144
145 }