1
2
3
4 package net.sourceforge.pmd.util;
5
6 import java.util.HashMap;
7 import java.util.Iterator;
8 import java.util.Map;
9
10
11
12
13
14
15
16
17
18 public class TypeMap {
19
20 private Map<String, Class<?>> typesByName;
21
22
23
24
25
26
27 public TypeMap(int initialSize) {
28 typesByName = new HashMap<String, Class<?>>(initialSize);
29 }
30
31
32
33
34
35
36 public TypeMap(Class<?>... types) {
37 this(types.length);
38 add(types);
39 }
40
41
42
43
44
45
46
47
48
49 @SuppressWarnings("PMD.CompareObjectsWithEquals")
50 public void add(Class<?> type) {
51 final String shortName = ClassUtil.withoutPackageName(type.getName());
52 Class<?> existingType = typesByName.get(shortName);
53 if (existingType == null) {
54 typesByName.put(type.getName(), type);
55 typesByName.put(shortName, type);
56 return;
57 }
58
59 if (existingType != type) {
60 throw new IllegalArgumentException("Short name collision between existing " + existingType + " and new "
61 + type);
62 }
63 }
64
65
66
67
68
69
70
71 public boolean contains(Class<?> type) {
72 return typesByName.containsValue(type);
73 }
74
75
76
77
78
79
80
81 public boolean contains(String typeName) {
82 return typesByName.containsKey(typeName);
83 }
84
85
86
87
88
89
90
91 public Class<?> typeFor(String typeName) {
92 return typesByName.get(typeName);
93 }
94
95
96
97
98
99
100 public void add(Class<?>... types) {
101 for (Class<?> element : types) {
102 add(element);
103 }
104 }
105
106
107
108
109
110
111
112 public Map<Class<?>, String> asInverseWithShortName() {
113 Map<Class<?>, String> inverseMap = new HashMap<Class<?>, String>(typesByName.size() / 2);
114
115 Iterator<Map.Entry<String,Class<?>>> iter = typesByName.entrySet().iterator();
116 while (iter.hasNext()) {
117 Map.Entry<String,Class<?>> entry = iter.next();
118 storeShortest(inverseMap, entry.getValue(), entry.getKey());
119 }
120
121 return inverseMap;
122 }
123
124
125
126
127
128
129
130 public int size() {
131 return typesByName.size();
132 }
133
134
135
136
137
138
139
140
141
142 private void storeShortest(Map<Class<?>, String> map, Class<?> key, String value) {
143 String existingValue = map.get(key);
144
145 if (existingValue == null) {
146 map.put(key, value);
147 return;
148 }
149
150 if (existingValue.length() < value.length()) {
151 return;
152 }
153
154 map.put(key, value);
155 }
156 }