01: package org.kohsuke.args4j;
02:
03: import org.kohsuke.args4j.spi.Setter;
04:
05: import java.lang.reflect.Field;
06: import java.lang.reflect.ParameterizedType;
07: import java.lang.reflect.Type;
08: import java.util.ArrayList;
09: import java.util.List;
10:
11: /**
12: * {@link Setter} that sets multiple values to a collection {@link Field}.
13: *
14: * @author Kohsuke Kawaguchi
15: */
16: final class MultiValueFieldSetter implements Setter {
17: private final Object bean;
18: private final Field f;
19:
20: public MultiValueFieldSetter(Object bean, Field f) {
21: this .bean = bean;
22: this .f = f;
23:
24: if (!List.class.isAssignableFrom(f.getType()))
25: throw new IllegalAnnotationError(
26: Messages.ILLEGAL_FIELD_SIGNATURE
27: .format(f.getType()));
28: }
29:
30: public boolean isMultiValued() {
31: return true;
32: }
33:
34: public Class getType() {
35: // TODO: compute this correctly
36: Type t = f.getGenericType();
37: if (t instanceof ParameterizedType) {
38: ParameterizedType pt = (ParameterizedType) t;
39: t = pt.getActualTypeArguments()[0];
40: if (t instanceof Class)
41: return (Class) t;
42: }
43: return Object.class;
44: }
45:
46: public void addValue(Object value) {
47: try {
48: doAddValue(bean, value);
49: } catch (IllegalAccessException _) {
50: // try again
51: f.setAccessible(true);
52: try {
53: doAddValue(bean, value);
54: } catch (IllegalAccessException e) {
55: throw new IllegalAccessError(e.getMessage());
56: }
57: }
58: }
59:
60: private void doAddValue(Object bean, Object value)
61: throws IllegalAccessException {
62: Object o = f.get(bean);
63: if (o == null) {
64: o = new ArrayList();
65: f.set(bean, o);
66: }
67: if (!(o instanceof List))
68: throw new IllegalAnnotationError("type of " + f
69: + " is not a List");
70:
71: ((List) o).add(value);
72: }
73: }
|