01: package org.vraptor.reflection;
02:
03: import java.lang.reflect.Array;
04: import java.lang.reflect.Type;
05:
06: import org.vraptor.component.ComponentInstantiationException;
07:
08: /**
09: * An array implementation.
10: *
11: * @author Guilherme Silveira
12: */
13: public class ArrayDealer implements SetDealer {
14:
15: public Object resizeAndSet(Object object, int position,
16: boolean mayCreate, Type type) throws SettingException {
17:
18: int length = position + 1;
19:
20: if (object == null) {
21: if (!mayCreate) {
22: throw new SettingException("Unable to create array");
23: }
24: object = Array.newInstance((Class<?>) type, 0);
25: }
26:
27: int realLen = Array.getLength(object);
28:
29: if (realLen >= length) {
30: return object;
31: }
32:
33: if ((!mayCreate) || length != realLen + 1) {
34: throw new SettingException(
35: "Invalid array index - probably missed one object in between: "
36: + position);
37: }
38:
39: // reinstantiates the array
40: Object newArray = Array.newInstance(object.getClass()
41: .getComponentType(), length);
42: for (int j = 0; j < realLen; j++) {
43: Array.set(newArray, j, Array.get(object, j));
44: }
45: try {
46: Array.set(newArray, position, ReflectionUtil
47: .instantiate(object.getClass().getComponentType()));
48: } catch (ComponentInstantiationException e) {
49: throw new SettingException(e.getMessage(), e);
50: }
51: return newArray;
52:
53: }
54:
55: public Object getPosition(Object object, int arrayPosition,
56: boolean mayCreate) {
57: return Array.get(object, arrayPosition);
58: }
59:
60: public Object resizeAndSet(Object array, int position, Object value)
61: throws SettingException {
62: int len = Array.getLength(array);
63: if (len > position) {
64: throw new SettingException(
65: "There is already an object in this position!");
66: }
67: if (len != position) {
68: throw new SettingException(
69: "Invalid array index - probably missed one object in between: "
70: + position);
71: }
72: Object newArray;
73: if (len < position + 1) {
74: // reinstantiates the array if needed
75: newArray = Array.newInstance(array.getClass()
76: .getComponentType(), position + 1);
77: for (int j = 0; j < Array.getLength(array); j++) {
78: Array.set(newArray, j, Array.get(array, j));
79: }
80: } else {
81: newArray = array;
82: }
83: Array.set(newArray, position, value);
84: return newArray;
85: }
86:
87: public Class getType(Type type) {
88: return ((Class) type).getComponentType();
89: }
90:
91: }
|