File: Types.java

package info (click to toggle)
libjtype-java 0.1.3-4
  • links: PTS, VCS
  • area: main
  • in suites: buster, stretch
  • size: 380 kB
  • ctags: 829
  • sloc: java: 4,599; xml: 210; sh: 13; makefile: 5
file content (394 lines) | stat: -rw-r--r-- 11,232 bytes parent folder | download | duplicates (2)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/*
 * Copyright 2009 IIZUKA Software Technologies Ltd
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.jtype;

import static com.googlecode.jtype.Utils.checkNotNull;

import java.io.Serializable;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Factory for creating types.
 * 
 * @author Mark Hobson
 * @version $Id: Types.java 110 2011-11-23 17:19:43Z markhobson $
 * @see Type
 */
public final class Types
{
	// constants --------------------------------------------------------------
	
	private static final WildcardType UNBOUNDED_WILDCARD_TYPE = wildcardType(null, null);
	
	private static final Pattern ARRAY_PATTERN = Pattern.compile("\\[\\s*\\]$");

	private static final Pattern UPPER_BOUND_PATTERN = Pattern.compile("^\\?\\s+extends\\s+");
	
	private static final Pattern LOWER_BOUND_PATTERN = Pattern.compile("^\\?\\s+super\\s+");
	
	// constructors -----------------------------------------------------------
	
	private Types()
	{
		throw new AssertionError();
	}
	
	// public methods ---------------------------------------------------------
	
	/**
	 * Creates a type variable for the specified declaration, name and bounds.
	 * 
	 * @param <D>
	 *            the type of generic declaration that declared the type variable
	 * @param declaration
	 *            the generic declaration that declared the type variable
	 * @param name
	 *            the name of the type variable
	 * @param bounds
	 *            the upper bounds of the type variable
	 * @return the type variable
	 */
	public static <D extends GenericDeclaration> TypeVariable<D> typeVariable(D declaration, String name,
		Type... bounds)
	{
		return (TypeVariable<D>) Proxy.newProxyInstance(
				Types.class.getClassLoader(),
				new Class[]{TypeVariable.class},
				new TypeVariableInvocationHandler(new DefaultTypeVariable<D>(declaration, name, bounds)));
	}
	
	/**
	 * Creates a generic array type for the specified component type.
	 * 
	 * @param componentType
	 *            the component type
	 * @return the generic array type
	 */
	public static GenericArrayType genericArrayType(Type componentType)
	{
		return new DefaultGenericArrayType(componentType);
	}
	
	/**
	 * Creates a parameterized type for the specified raw type and actual type arguments.
	 * 
	 * @param rawType
	 *            the raw type
	 * @param actualTypeArguments
	 *            the actual type arguments
	 * @return the parameterized type
	 * @throws MalformedParameterizedTypeException
	 *             if the raw type is not a parameterized type or the number of actual type arguments differs from those
	 *             defined on the raw type
	 */
	public static ParameterizedType parameterizedType(Class<?> rawType, Type... actualTypeArguments)
	{
		return new DefaultParameterizedType(null, rawType, actualTypeArguments);
	}
	
	/**
	 * Creates a parameterized type for the specified raw type with unbounded wildcard actual type arguments.
	 * 
	 * @param rawType
	 *            the raw type
	 * @return the parameterized type
	 * @throws MalformedParameterizedTypeException
	 *             if the raw type is not a parameterized type
	 */
	public static ParameterizedType unboundedParameterizedType(Class<?> rawType)
	{
		checkNotNull(rawType, "rawType");
		
		int typeParameterCount = rawType.getTypeParameters().length;
		
		Type[] actualTypeArguments = new Type[typeParameterCount];
		Arrays.fill(actualTypeArguments, unboundedWildcardType());
		
		return parameterizedType(rawType, actualTypeArguments);
	}

	/**
	 * Creates an unbounded wildcard type.
	 * 
	 * @return the wildcard type
	 */
	public static WildcardType unboundedWildcardType()
	{
		return UNBOUNDED_WILDCARD_TYPE;
	}
	
	/**
	 * Creates a wildcard type with the specified upper bound.
	 * 
	 * @param upperBound
	 *            the upper bound type
	 * @return the wildcard type
	 */
	public static WildcardType upperBoundedWildcardType(Type upperBound)
	{
		checkNotNull(upperBound, "upperBound");
		
		return wildcardType(new Type[] {upperBound}, null);
	}
	
	/**
	 * Creates a wildcard type with the specified lower bound.
	 * 
	 * @param lowerBound
	 *            the lower bound type
	 * @return the wildcard type
	 */
	public static WildcardType lowerBoundedWildcardType(Type lowerBound)
	{
		checkNotNull(lowerBound, "lowerBound");
		
		return wildcardType(null, new Type[] {lowerBound});
	}
	
	/**
	 * Returns a type that corresponds to the specified string.
	 * 
	 * @param typeName
	 *            the string to be parsed
	 * @return the type
	 */
	public static Type valueOf(String typeName)
	{
		return valueOf(typeName, (Set<String>) null);
	}
	
	/**
	 * Returns a type that corresponds to the specified string using the specified import context.
	 * 
	 * @param typeName
	 *            the string to be parsed
	 * @param imports
	 *            the fully qualified class names to use when an unqualified class name is encountered
	 * @return the type
	 * @throws IllegalArgumentException
	 *             if the import context contains duplicate entries for an unqualified class name
	 */
	public static Type valueOf(String typeName, Set<String> imports)
	{
		checkNotNull(typeName, "typeName");
		
		Map<String, String> importMap = createImportMap(imports);
		
		return valueOf(typeName, importMap);
	}
	
	// private methods --------------------------------------------------------
	
	private static WildcardType wildcardType(Type[] upperBounds, Type[] lowerBounds)
	{
		return new DefaultWildcardType(upperBounds, lowerBounds);
	}
	
	private static Map<String, String> createImportMap(Set<String> imports)
	{
		if (imports == null)
		{
			return Collections.emptyMap();
		}
		
		Map<String, String> importMap = new HashMap<String, String>();
		
		for (String className : imports)
		{
			String simpleClassName = ClassUtils.getSimpleClassName(className);
			
			if (importMap.containsKey(simpleClassName))
			{
				throw new IllegalArgumentException("Duplicate imports: " + importMap.get(simpleClassName) + " and "
					+ className);
			}
			
			importMap.put(simpleClassName, className);
		}
		
		return importMap;
	}
	
	private static Type valueOf(String typeName, Map<String, String> imports)
	{
		typeName = typeName.trim();
		
		// handle arrays
		
		Matcher arrayMatcher = ARRAY_PATTERN.matcher(typeName);
		
		if (arrayMatcher.find())
		{
			String componentName = typeName.substring(0, arrayMatcher.start());
			
			Type componentType = valueOf(componentName, imports);
			
			return TypeUtils.getArrayType(componentType);
		}
		
		// handle wildcards
		
		if (typeName.startsWith("?"))
		{
			return parseWildcardType(typeName, imports);
		}
		
		// handle classes
		
		int argStart = typeName.indexOf('<');
		
		if (argStart == -1)
		{
			return parseClass(typeName, imports);
		}
		
		// handle parameterized types
		
		int argEnd = typeName.lastIndexOf('>');
		
		if (argEnd == -1)
		{
			throw new IllegalArgumentException("Mismatched type argument delimiters: " + typeName);
		}
		
		String rawTypeName = typeName.substring(0, argStart).trim();
		Class<?> rawType = parseClass(rawTypeName, imports);
		
		String[] actualTypeArgumentNames = typeName.substring(argStart + 1, argEnd).split(",");
		Type[] actualTypeArguments = new Type[actualTypeArgumentNames.length];
		
		for (int i = 0; i < actualTypeArgumentNames.length; i++)
		{
			actualTypeArguments[i] = valueOf(actualTypeArgumentNames[i], imports);
		}
		
		return parameterizedType(rawType, actualTypeArguments);
	}
	
	private static Class<?> parseClass(String className, Map<String, String> imports)
	{
		Class<?> klass = ClassUtils.valueOf(className);
		
		if (klass != null)
		{
			return klass;
		}
		
		if (!className.contains(".") && imports.containsKey(className))
		{
			String qualifiedClassName = imports.get(className);
			
			klass = ClassUtils.valueOf(qualifiedClassName);
			
			if (klass != null)
			{
				return klass;
			}
		}
		
		throw new IllegalArgumentException("Class not found: " + className);
	}
	
	private static WildcardType parseWildcardType(String typeName, Map<String, String> imports)
	{
		Type[] upperBounds;
		Type[] lowerBounds;
		
		Matcher upperBoundMatcher;
		Matcher lowerBoundMatcher;
		
		if ("?".equals(typeName))
		{
			upperBounds = null;
			lowerBounds = null;
		}
		else if ((upperBoundMatcher = UPPER_BOUND_PATTERN.matcher(typeName)).find())
		{
			String upperBoundName = typeName.substring(upperBoundMatcher.end());
			Type upperBound = valueOf(upperBoundName, imports);
			
			upperBounds = new Type[] {upperBound};
			lowerBounds = null;
		}
		else if ((lowerBoundMatcher = LOWER_BOUND_PATTERN.matcher(typeName)).find())
		{
			String lowerBoundName = typeName.substring(lowerBoundMatcher.end());
			Type lowerBound = valueOf(lowerBoundName, imports);
			
			upperBounds = null;
			lowerBounds = new Type[] {lowerBound};
		}
		else
		{
			throw new IllegalArgumentException("Invalid wildcard type: " + typeName);
		}
		
		return wildcardType(upperBounds, lowerBounds);
	}

	private static class TypeVariableInvocationHandler implements InvocationHandler, Serializable {
		private static final Map<String, Method> typeVariableMethods = new HashMap<String, Method>();
		static {
			for (Method method : DefaultTypeVariable.class.getMethods()) {
				if (method.getDeclaringClass().equals(DefaultTypeVariable.class)) {
					typeVariableMethods.put(method.getName(), method);
				}
			}
		}

		private final DefaultTypeVariable<?> typeVariable;

		public TypeVariableInvocationHandler(DefaultTypeVariable<?> typeVariable) {
			this.typeVariable = typeVariable;
		}

		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			String methodName = method.getName();

			if ("toString".equals(methodName)) {
				return TypeUtils.toString((Type) proxy);
			}

			Method typeVariableMethod = typeVariableMethods.get(methodName);
			if (typeVariableMethod == null) {
				throw new UnsupportedOperationException(methodName);
			} else {
				try {
					return typeVariableMethod.invoke(typeVariable, args);
				} catch (InvocationTargetException e) {
					throw e.getCause();
				}
			}
		}
	}
}