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