View Javadoc
1   package org.pojomatic.internal;
2   
3   import java.lang.reflect.Array;
4   import java.util.ArrayList;
5   import java.util.List;
6   import java.util.Objects;
7   
8   public class ArrayType implements Type {
9     private final Type componentType;
10    private final List<Object> sampleValues;
11  
12    public ArrayType(Type componentType) {
13      this.componentType = componentType;
14      sampleValues = new ArrayList<>();
15      sampleValues.add(null);
16      for (int size = 0; size < componentType.getSampleValues().size(); size++) {
17        Object array = Array.newInstance(componentType.getClazz(), size);
18        for (int i = 0; i < size; i++) {
19          Array.set(array, i, componentType.getSampleValues().get(i));
20        }
21        sampleValues.add(array);
22      }
23    }
24  
25    @Override
26    public Class<?> getClazz() {
27      return Array.newInstance(componentType.getClazz(), 0).getClass();
28    }
29  
30    @Override
31    public List<Object> getSampleValues() {
32      return sampleValues;
33    }
34  
35    @Override
36    public String toString() {
37      return componentType.toString() + "[]";
38    }
39  
40    @Override
41    public int hashCode(Object value) {
42      return value == null ? 0 : arrayToList(value).hashCode();
43    }
44    @Override
45    public int deepHashCode(Object value) {
46      if (value == null) {
47        return 0;
48      }
49      else {
50        int hash = 1;
51        for (Object element: arrayToList(value)) {
52          hash = hash*31 + componentType.deepHashCode(element);
53        }
54        return hash;
55      }
56    }
57  
58    @Override
59    public String toString(Object value) {
60      if (value == null) {
61        return "null";
62      }
63      else {
64        ArrayList<String> strings = new ArrayList<>();
65        for (Object element: arrayToList(value)) {
66          if (componentType instanceof ArrayType) {
67            strings.add(Objects.toString(element));
68          }
69          else {
70            strings.add(componentType.toString(element));
71          }
72        }
73        return strings.toString();
74      }
75    }
76  
77    @Override
78    public String deepToString(Object value) {
79      if (value == null) {
80        return "null";
81      }
82      else {
83        ArrayList<String> strings = new ArrayList<>();
84        for (Object element: arrayToList(value)) {
85          strings.add(componentType.deepToString(element));
86        }
87        return strings.toString();
88      }
89    }
90  
91    private static List<?> arrayToList(Object array) {
92      List<Object> result = new ArrayList<>();
93      for (int i = 0; i < Array.getLength(array); i++) {
94        result.add(Array.get(array, i));
95      }
96      return result;
97    }
98  
99    @Override
100   public int arrayDepth() {
101     return componentType.arrayDepth() + 1;
102   }
103 }