1 |
| |
2 |
| |
3 |
| |
4 |
| |
5 |
| |
6 |
| |
7 |
| |
8 |
| |
9 |
| |
10 |
| |
11 |
| |
12 |
| |
13 |
| |
14 |
| |
15 |
| |
16 |
| package org.rblasch.convert.converters.collections; |
17 |
| |
18 |
| import org.rblasch.convert.ConversionFailedException; |
19 |
| import org.rblasch.convert.MetaConverter; |
20 |
| import org.rblasch.convert.assertion.Assertion; |
21 |
| import org.rblasch.convert.converters.AbstractConverter; |
22 |
| import org.rblasch.convert.type.ClassType; |
23 |
| import org.rblasch.convert.type.PrimitiveType; |
24 |
| import org.rblasch.convert.type.Type; |
25 |
| import org.rblasch.convert.type.Types; |
26 |
| |
27 |
| import java.lang.reflect.Array; |
28 |
| |
29 |
| |
30 |
| |
31 |
| |
32 |
| public class ArrayConverter extends AbstractConverter { |
33 |
| private final Type sourceCType, destinationCType; |
34 |
| private final MetaConverter cConverter; |
35 |
| |
36 |
27
| public ArrayConverter(final Type sourceCType, final Type destinationCType, final MetaConverter cConverter) {
|
37 |
27
| this.sourceCType = sourceCType;
|
38 |
27
| this.destinationCType = destinationCType;
|
39 |
27
| this.cConverter = cConverter;
|
40 |
| } |
41 |
| |
42 |
231
| public Type getSourceType() {
|
43 |
231
| return Types.findPTypeByType(Types.findTypeByName("array"), sourceCType);
|
44 |
| } |
45 |
| |
46 |
231
| public Type getDestinationType() {
|
47 |
231
| return Types.findPTypeByType(Types.findTypeByName("array"), destinationCType);
|
48 |
| } |
49 |
| |
50 |
27
| public int getWeight() {
|
51 |
27
| return 100;
|
52 |
| } |
53 |
| |
54 |
1
| public Object convert(final Object obj) throws Exception {
|
55 |
1
| Assertion.ensure(sourceCType instanceof ClassType
|
56 |
| || sourceCType instanceof PrimitiveType, "source component must be class or primitive"); |
57 |
1
| Assertion.ensure(destinationCType instanceof ClassType
|
58 |
| || destinationCType instanceof PrimitiveType, "destination component must be class or primitive"); |
59 |
| |
60 |
1
| final Object in = obj;
|
61 |
1
| final Class outComponentClass;
|
62 |
1
| if (destinationCType instanceof ClassType) {
|
63 |
0
| outComponentClass = ((ClassType) destinationCType).getTheClass();
|
64 |
1
| } else if (destinationCType instanceof PrimitiveType) {
|
65 |
1
| outComponentClass = ((PrimitiveType) destinationCType).getTheClass();
|
66 |
| } else { |
67 |
0
| throw new ConversionFailedException("Illegal source component type " + sourceCType);
|
68 |
| } |
69 |
| |
70 |
1
| final Object out = Array.newInstance(outComponentClass, Array.getLength(in));
|
71 |
1
| for (int i = 0; i < Array.getLength(in); ++i) {
|
72 |
3
| Array.set(out, i, cConverter.getConverter().convert(Array.get(in, i)));
|
73 |
| } |
74 |
| |
75 |
1
| return out;
|
76 |
| } |
77 |
| } |