01: /*
02: * Created on 6 Oct 2006
03: */
04: package uk.org.ponder.beanutil.support;
05:
06: import java.lang.reflect.Array;
07: import java.util.List;
08:
09: import uk.org.ponder.beanutil.PropertyAccessor;
10: import uk.org.ponder.saxalizer.mapping.ContainerTypeRegistry;
11: import uk.org.ponder.util.EnumerationConverter;
12:
13: /** Accessor for numeric indexed properties (held in Arrays or Lists) * */
14:
15: public class IndexedPropertyAccessor implements PropertyAccessor {
16:
17: public void setContainerTypeRegistry(
18: ContainerTypeRegistry containertyperegistry) {
19: this .ctr = containertyperegistry;
20: }
21:
22: public static boolean isIndexed(Class c) {
23: return (c.isArray() || List.class.isAssignableFrom(c));
24: }
25:
26: private ContainerTypeRegistry ctr;
27:
28: public boolean canGet(String name) {
29: return true;
30: }
31:
32: public boolean canSet(String name) {
33: return true;
34: }
35:
36: public Object getProperty(Object parent, String name) {
37: int index = Integer.parseInt(name);
38: if (parent.getClass().isArray()) {
39: return Array.get(parent, index);
40: } else {
41: return ((List) parent).get(index);
42: }
43: }
44:
45: public Class getPropertyType(Object parent, String name) {
46: Class ctype = ctr.getContaineeType(parent);
47: if (ctype == null) {
48: return String.class;
49: } else
50: return ctype;
51: }
52:
53: public boolean isMultiple(Object parent, String name) {
54: return EnumerationConverter.isDenumerable(getPropertyType(
55: parent, name));
56: }
57:
58: public void setProperty(Object parent, String name, Object value) {
59: int index = Integer.parseInt(name);
60: if (parent.getClass().isArray()) {
61: Array.set(parent, index, value);
62: } else {
63: ((List) parent).set(index, value);
64: }
65:
66: }
67:
68: public void unlink(Object parent, String name) {
69: int index = Integer.parseInt(name);
70: if (parent instanceof List) {
71: ((List) parent).remove(index);
72: } else {
73: throw new UnsupportedOperationException(
74: "Cannot remove element from array "
75: + parent.getClass());
76: }
77: }
78:
79: }
|