1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.kuali.rice.kns.web.struts.pojo;
17
18
19 import java.lang.reflect.Array;
20
21
22
23
24
25
26
27 public class ArrayUtils {
28
29
30
31
32
33
34
35
36 public static void setArrayValue(Object array, Class type, Object value, int index) {
37 if (!type.isPrimitive())
38 Array.set(array, index, value);
39 else if (type.isAssignableFrom(Boolean.TYPE))
40 Array.setBoolean(array, index, (Boolean) value);
41 else if (type.isAssignableFrom(Character.TYPE))
42 Array.setChar(array, index, (Character) value);
43 else if (type.isAssignableFrom(Byte.TYPE))
44 Array.setByte(array, index, (Byte) value);
45 else if (type.isAssignableFrom(Integer.TYPE))
46 Array.setInt(array, index, (Integer) value);
47 else if (type.isAssignableFrom(Short.TYPE))
48 Array.setShort(array, index, (Short) value);
49 else if (type.isAssignableFrom(Long.TYPE))
50 Array.setLong(array, index, (Long) value);
51 else if (type.isAssignableFrom(Float.TYPE))
52 Array.setFloat(array, index, (Float) value);
53 else if (type.isAssignableFrom(Double.TYPE))
54 Array.setDouble(array, index, (Double) value);
55 }
56
57 public static Object toObject(Object value) {
58 if (!value.getClass().isArray())
59 return value;
60
61 Class type = value.getClass().getComponentType();
62 if (Array.getLength(value) == 0)
63 return null;
64 if (!type.isPrimitive())
65 return Array.get(value, 0);
66 if (boolean.class.isAssignableFrom(type))
67 return Array.getBoolean(value, 0);
68 if (char.class.isAssignableFrom(type))
69 return Array.getChar(value, 0);
70 if (byte.class.isAssignableFrom(type))
71 return Array.getByte(value, 0);
72 if (int.class.isAssignableFrom(type))
73 return Array.getInt(value, 0);
74 if (long.class.isAssignableFrom(type))
75 return Array.getLong(value, 0);
76 if (short.class.isAssignableFrom(type))
77 return Array.getShort(value, 0);
78 if (double.class.isAssignableFrom(type))
79 return Array.getDouble(value, 0);
80 if (float.class.isAssignableFrom(type))
81 return Array.getFloat(value, 0);
82
83 return null;
84 }
85
86 public static Object toString(Object array, Class type) {
87 if (boolean.class.isAssignableFrom(type))
88 return Boolean.toString(((boolean[]) array)[0]);
89 if (char.class.isAssignableFrom(type))
90 return Character.toString(((char[]) array)[0]);
91 if (byte.class.isAssignableFrom(type))
92 return Byte.toString(((byte[]) array)[0]);
93 if (int.class.isAssignableFrom(type))
94 return Integer.toString(((int[]) array)[0]);
95 if (long.class.isAssignableFrom(type))
96 return Long.toString(((long[]) array)[0]);
97 if (short.class.isAssignableFrom(type))
98 return Short.toString(((short[]) array)[0]);
99 if (double.class.isAssignableFrom(type))
100 return Double.toString(((double[]) array)[0]);
101 if (float.class.isAssignableFrom(type))
102 return Float.toString(((float[]) array)[0]);
103
104 return ((String[]) array)[0];
105 }
106 }