01: package com.jidesoft.converter;
02:
03: import java.awt.*;
04: import java.lang.reflect.Array;
05:
06: /**
07: * Converts an array to a string and converts a string to an array.
08: */
09: public class DefaultArrayConverter extends ArrayConverter {
10: public DefaultArrayConverter(String separator, Class<?> elementClass) {
11: super (separator, -1, elementClass);
12: }
13:
14: public String toString(Object object, ConverterContext context) {
15: if (object == null) {
16: return "";
17: } else {
18: if (object.getClass().isArray()) {
19: Object[] objects;
20: if (getElementClass() == Object.class) {
21: objects = (Object[]) object;
22: } else {
23: objects = new Object[Array.getLength(object)];
24: }
25: for (int i = 0; i < objects.length; i++) {
26: objects[i] = Array.get(object, i);
27: }
28: return arrayToString(objects, context);
29: } else {
30: return ObjectConverterManager.toString(object,
31: getElementClass(), context);
32: }
33: }
34: }
35:
36: public boolean supportToString(Object object,
37: ConverterContext context) {
38: return true;
39: }
40:
41: public Object fromString(String string, ConverterContext context) {
42: if (string == null || "".equals(string)) {
43: return new Object[0];
44: } else {
45: Object[] objects = arrayFromString(string, context);
46: if (getElementClass() == Object.class) {
47: return objects;
48: }
49: Object array = Array.newInstance(getElementClass(),
50: objects.length);
51: for (int i = 0; i < objects.length; i++) {
52: Object object = objects[i];
53: Array.set(array, i, object);
54: }
55: return array;
56: }
57: }
58:
59: public boolean supportFromString(String string,
60: ConverterContext context) {
61: return true;
62: }
63:
64: public static void main(String[] args) {
65: System.out.println(new DefaultArrayConverter(";", int.class)
66: .toString(new int[] { 2, 3, 2, 4 }, null));
67: System.out.println(new DefaultArrayConverter(";", int.class)
68: .fromString("2;3;2;4", null));
69:
70: System.out.println(new DefaultArrayConverter(";", Color.class)
71: .toString(new Color[] { Color.RED, Color.YELLOW,
72: Color.GREEN }, HexColorConverter.CONTEXT_HEX));
73: System.out.println(new DefaultArrayConverter(";", Color.class)
74: .fromString("#FF0000;#FFFF00;#00FF00",
75: HexColorConverter.CONTEXT_HEX));
76: System.out.println(new DefaultArrayConverter(";", Object.class)
77: .fromString("#FF0000;#FFFF00;#00FF00", null));
78: }
79: }
|