001 /*
002 * Copyright (C) 2006 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package com.google.common.reflect;
018
019 import static com.google.common.base.Preconditions.checkArgument;
020 import static com.google.common.base.Preconditions.checkNotNull;
021 import static com.google.common.base.Preconditions.checkState;
022
023 import com.google.common.annotations.Beta;
024 import com.google.common.annotations.VisibleForTesting;
025 import com.google.common.base.Predicate;
026 import com.google.common.collect.FluentIterable;
027 import com.google.common.collect.ForwardingSet;
028 import com.google.common.collect.ImmutableList;
029 import com.google.common.collect.ImmutableMap;
030 import com.google.common.collect.ImmutableSet;
031 import com.google.common.collect.Maps;
032 import com.google.common.collect.Ordering;
033
034 import java.io.Serializable;
035 import java.lang.reflect.GenericArrayType;
036 import java.lang.reflect.ParameterizedType;
037 import java.lang.reflect.Type;
038 import java.lang.reflect.TypeVariable;
039 import java.lang.reflect.WildcardType;
040 import java.util.Arrays;
041 import java.util.Comparator;
042 import java.util.Map;
043 import java.util.Set;
044
045 import javax.annotation.Nullable;
046
047 /**
048 * A {@link Type} with generics.
049 *
050 * <p>Operations that are otherwise only available in {@link Class} are implemented to support
051 * {@code Type}, for example {@link #isAssignableFrom}, {@link #isArray} and {@link
052 * #getComponentType}. It also provides additional utilities such as {@link #getTypes} and {@link
053 * #resolveType} etc.
054 *
055 * <p>There are three ways to get a {@code TypeToken} instance: <ul>
056 * <li>Wrap a {@code Type} obtained via reflection. For example: {@code
057 * TypeToken.of(method.getGenericReturnType())}.
058 * <li>Capture a generic type with a (usually anonymous) subclass. For example: <pre> {@code
059 *
060 * new TypeToken<List<String>>() {}
061 * }</pre>
062 * Note that it's critical that the actual type argument is carried by a subclass.
063 * The following code is wrong because it only captures the {@code <T>} type variable
064 * of the {@code listType()} method signature; while {@code <String>} is lost in erasure:
065 * <pre> {@code
066 *
067 * class Util {
068 * static <T> TypeToken<List<T>> listType() {
069 * return new TypeToken<List<T>>() {};
070 * }
071 * }
072 *
073 * TypeToken<List<String>> stringListType = Util.<String>listType();
074 * }</pre>
075 * <li>Capture a generic type with a (usually anonymous) subclass and resolve it against
076 * a context class that knows what the type parameters are. For example: <pre> {@code
077 * abstract class IKnowMyType<T> {
078 * TypeToken<T> type = new TypeToken<T>(getClass()) {};
079 * }
080 * new IKnowMyType<String>() {}.type => String
081 * }</pre>
082 * </ul>
083 *
084 * <p>{@code TypeToken} is serializable when no type variable is contained in the type.
085 *
086 * <p>Note to Guice users: {@code} TypeToken is similar to Guice's {@code TypeLiteral} class,
087 * but with one important difference: it supports non-reified types such as {@code T},
088 * {@code List<T>} or even {@code List<? extends Number>}; while TypeLiteral does not.
089 * TypeToken is also serializable and offers numerous additional utility methods.
090 *
091 * @author Bob Lee
092 * @author Sven Mawson
093 * @author Ben Yu
094 * @since 12.0
095 */
096 @Beta
097 @SuppressWarnings("serial") // SimpleTypeToken is the serialized form.
098 public abstract class TypeToken<T> extends TypeCapture<T> implements Serializable {
099
100 private final Type runtimeType;
101
102 /** Resolver for resolving types with {@link #runtimeType} as context. */
103 private transient TypeResolver typeResolver;
104
105 /**
106 * Constructs a new type token of {@code T}.
107 *
108 * <p>Clients create an empty anonymous subclass. Doing so embeds the type
109 * parameter in the anonymous class's type hierarchy so we can reconstitute
110 * it at runtime despite erasure.
111 *
112 * <p>For example: <pre> {@code
113 *
114 * TypeToken<List<String>> t = new TypeToken<List<String>>() {};
115 * }</pre>
116 */
117 protected TypeToken() {
118 this.runtimeType = capture();
119 checkState(!(runtimeType instanceof TypeVariable),
120 "Cannot construct a TypeToken for a type variable.\n" +
121 "You probably meant to call new TypeToken<%s>(getClass()) " +
122 "that can resolve the type variable for you.\n" +
123 "If you do need to create a TypeToken of a type variable, " +
124 "please use TypeToken.of() instead.", runtimeType);
125 }
126
127 /**
128 * Constructs a new type token of {@code T} while resolving free type variables in the context of
129 * {@code declaringClass}.
130 *
131 * <p>Clients create an empty anonymous subclass. Doing so embeds the type
132 * parameter in the anonymous class's type hierarchy so we can reconstitute
133 * it at runtime despite erasure.
134 *
135 * <p>For example: <pre> {@code
136 *
137 * abstract class IKnowMyType<T> {
138 * TypeToken<T> getMyType() {
139 * return new TypeToken<T>(getClass()) {};
140 * }
141 * }
142 *
143 * new IKnowMyType<String>() {}.getMyType() => String
144 * }</pre>
145 */
146 protected TypeToken(Class<?> declaringClass) {
147 Type captured = super.capture();
148 if (captured instanceof Class) {
149 this.runtimeType = captured;
150 } else {
151 this.runtimeType = of(declaringClass).resolveType(captured).runtimeType;
152 }
153 }
154
155 private TypeToken(Type type) {
156 this.runtimeType = checkNotNull(type);
157 }
158
159 /** Returns an instance of type token that wraps {@code type}. */
160 public static <T> TypeToken<T> of(Class<T> type) {
161 return new SimpleTypeToken<T>(type);
162 }
163
164 /** Returns an instance of type token that wraps {@code type}. */
165 public static TypeToken<?> of(Type type) {
166 return new SimpleTypeToken<Object>(type);
167 }
168
169 /**
170 * Returns the raw type of {@code T}. Formally speaking, if {@code T} is returned by
171 * {@link java.lang.reflect.Method#getGenericReturnType}, the raw type is what's returned by
172 * {@link java.lang.reflect.Method#getReturnType} of the same method object. Specifically:
173 * <ul>
174 * <li>If {@code T} is a {@code Class} itself, {@code T} itself is returned.
175 * <li>If {@code T} is a {@link ParameterizedType}, the raw type of the parameterized type is
176 * returned.
177 * <li>If {@code T} is a {@link GenericArrayType}, the returned type is the corresponding array
178 * class. For example: {@code List<Integer>[] => List[]}.
179 * <li>If {@code T} is a type variable or a wildcard type, the raw type of the first upper bound
180 * is returned. For example: {@code <X extends Foo> => Foo}.
181 * </ul>
182 */
183 public final Class<? super T> getRawType() {
184 Class<?> rawType = getRawType(runtimeType);
185 @SuppressWarnings("unchecked") // raw type is |T|
186 Class<? super T> result = (Class<? super T>) rawType;
187 return result;
188 }
189
190 /**
191 * Returns the raw type of the class or parameterized type; if {@code T} is type variable or
192 * wildcard type, the raw types of all its upper bounds are returned.
193 */
194 private ImmutableSet<Class<? super T>> getImmediateRawTypes() {
195 // Cast from ImmutableSet<Class<?>> to ImmutableSet<Class<? super T>>
196 @SuppressWarnings({"unchecked", "rawtypes"})
197 ImmutableSet<Class<? super T>> result = (ImmutableSet) getRawTypes(runtimeType);
198 return result;
199 }
200
201 /** Returns the represented type. */
202 public final Type getType() {
203 return runtimeType;
204 }
205
206 /**
207 * Returns a new {@code TypeToken} where type variables represented by {@code typeParam}
208 * are substituted by {@code typeArg}. For example, it can be used to construct
209 * {@code Map<K, V>} for any {@code K} and {@code V} type: <pre> {@code
210 *
211 * static <K, V> TypeToken<Map<K, V>> mapOf(
212 * TypeToken<K> keyType, TypeToken<V> valueType) {
213 * return new TypeToken<Map<K, V>>() {}
214 * .where(new TypeParameter<K>() {}, keyType)
215 * .where(new TypeParameter<V>() {}, valueType);
216 * }
217 * }</pre>
218 *
219 * @param <X> The parameter type
220 * @param typeParam the parameter type variable
221 * @param typeArg the actual type to substitute
222 */
223 public final <X> TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg) {
224 TypeResolver resolver = new TypeResolver()
225 .where(ImmutableMap.of(typeParam.typeVariable, typeArg.runtimeType));
226 // If there's any type error, we'd report now rather than later.
227 return new SimpleTypeToken<T>(resolver.resolveType(runtimeType));
228 }
229
230 /**
231 * Returns a new {@code TypeToken} where type variables represented by {@code typeParam}
232 * are substituted by {@code typeArg}. For example, it can be used to construct
233 * {@code Map<K, V>} for any {@code K} and {@code V} type: <pre> {@code
234 *
235 * static <K, V> TypeToken<Map<K, V>> mapOf(
236 * Class<K> keyType, Class<V> valueType) {
237 * return new TypeToken<Map<K, V>>() {}
238 * .where(new TypeParameter<K>() {}, keyType)
239 * .where(new TypeParameter<V>() {}, valueType);
240 * }
241 * }</pre>
242 *
243 * @param <X> The parameter type
244 * @param typeParam the parameter type variable
245 * @param typeArg the actual type to substitute
246 */
247 public final <X> TypeToken<T> where(TypeParameter<X> typeParam, Class<X> typeArg) {
248 return where(typeParam, of(typeArg));
249 }
250
251 /**
252 * Resolves the given {@code type} against the type context represented by this type.
253 * For example: <pre> {@code
254 *
255 * new TypeToken<List<String>>() {}.resolveType(
256 * List.class.getMethod("get", int.class).getGenericReturnType())
257 * => String.class
258 * }</pre>
259 */
260 public final TypeToken<?> resolveType(Type type) {
261 checkNotNull(type);
262 TypeResolver resolver = typeResolver;
263 if (resolver == null) {
264 resolver = (typeResolver = TypeResolver.accordingTo(runtimeType));
265 }
266 return of(resolver.resolveType(type));
267 }
268
269 private TypeToken<?> resolveSupertype(Type type) {
270 TypeToken<?> supertype = resolveType(type);
271 // super types' type mapping is a subset of type mapping of this type.
272 supertype.typeResolver = typeResolver;
273 return supertype;
274 }
275
276 /**
277 * Returns the generic superclass of this type or {@code null} if the type represents
278 * {@link Object} or an interface. This method is similar but different from {@link
279 * Class#getGenericSuperclass}. For example, {@code
280 * new TypeToken<StringArrayList>() {}.getGenericSuperclass()} will return {@code
281 * new TypeToken<ArrayList<String>>() {}}; while {@code
282 * StringArrayList.class.getGenericSuperclass()} will return {@code ArrayList<E>}, where {@code E}
283 * is the type variable declared by class {@code ArrayList}.
284 *
285 * <p>If this type is a type variable or wildcard, its first upper bound is examined and returned
286 * if the bound is a class or extends from a class. This means that the returned type could be a
287 * type variable too.
288 */
289 @Nullable
290 final TypeToken<? super T> getGenericSuperclass() {
291 if (runtimeType instanceof TypeVariable) {
292 // First bound is always the super class, if one exists.
293 return boundAsSuperclass(((TypeVariable<?>) runtimeType).getBounds()[0]);
294 }
295 if (runtimeType instanceof WildcardType) {
296 // wildcard has one and only one upper bound.
297 return boundAsSuperclass(((WildcardType) runtimeType).getUpperBounds()[0]);
298 }
299 Type superclass = getRawType().getGenericSuperclass();
300 if (superclass == null) {
301 return null;
302 }
303 @SuppressWarnings("unchecked") // super class of T
304 TypeToken<? super T> superToken = (TypeToken<? super T>) resolveSupertype(superclass);
305 return superToken;
306 }
307
308 @Nullable private TypeToken<? super T> boundAsSuperclass(Type bound) {
309 TypeToken<?> token = of(bound);
310 if (token.getRawType().isInterface()) {
311 return null;
312 }
313 @SuppressWarnings("unchecked") // only upper bound of T is passed in.
314 TypeToken<? super T> superclass = (TypeToken<? super T>) token;
315 return superclass;
316 }
317
318 /**
319 * Returns the generic interfaces that this type directly {@code implements}. This method is
320 * similar but different from {@link Class#getGenericInterfaces()}. For example, {@code
321 * new TypeToken<List<String>>() {}.getGenericInterfaces()} will return a list that contains
322 * {@code new TypeToken<Iterable<String>>() {}}; while {@code List.class.getGenericInterfaces()}
323 * will return an array that contains {@code Iterable<T>}, where the {@code T} is the type
324 * variable declared by interface {@code Iterable}.
325 *
326 * <p>If this type is a type variable or wildcard, its upper bounds are examined and those that
327 * are either an interface or upper-bounded only by interfaces are returned. This means that the
328 * returned types could include type variables too.
329 */
330 final ImmutableList<TypeToken<? super T>> getGenericInterfaces() {
331 if (runtimeType instanceof TypeVariable) {
332 return boundsAsInterfaces(((TypeVariable<?>) runtimeType).getBounds());
333 }
334 if (runtimeType instanceof WildcardType) {
335 return boundsAsInterfaces(((WildcardType) runtimeType).getUpperBounds());
336 }
337 ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
338 for (Type interfaceType : getRawType().getGenericInterfaces()) {
339 @SuppressWarnings("unchecked") // interface of T
340 TypeToken<? super T> resolvedInterface = (TypeToken<? super T>)
341 resolveSupertype(interfaceType);
342 builder.add(resolvedInterface);
343 }
344 return builder.build();
345 }
346
347 private ImmutableList<TypeToken<? super T>> boundsAsInterfaces(Type[] bounds) {
348 ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
349 for (Type bound : bounds) {
350 @SuppressWarnings("unchecked") // upper bound of T
351 TypeToken<? super T> boundType = (TypeToken<? super T>) of(bound);
352 if (boundType.getRawType().isInterface()) {
353 builder.add(boundType);
354 }
355 }
356 return builder.build();
357 }
358
359 /**
360 * Returns the set of interfaces and classes that this type is or is a subtype of. The returned
361 * types are parameterized with proper type arguments.
362 *
363 * <p>Subtypes are always listed before supertypes. But the reverse is not true. A type isn't
364 * necessarily a subtype of all the types following. Order between types without subtype
365 * relationship is arbitrary and not guaranteed.
366 *
367 * <p>If this type is a type variable or wildcard, upper bounds that are themselves type variables
368 * aren't included (their super interfaces and superclasses are).
369 */
370 public final TypeSet getTypes() {
371 return new TypeSet();
372 }
373
374 /**
375 * Returns the generic form of {@code superclass}. For example, if this is
376 * {@code ArrayList<String>}, {@code Iterable<String>} is returned given the
377 * input {@code Iterable.class}.
378 */
379 public final TypeToken<? super T> getSupertype(Class<? super T> superclass) {
380 checkArgument(superclass.isAssignableFrom(getRawType()),
381 "%s is not a super class of %s", superclass, this);
382 if (runtimeType instanceof TypeVariable) {
383 return getSupertypeFromUpperBounds(superclass, ((TypeVariable<?>) runtimeType).getBounds());
384 }
385 if (runtimeType instanceof WildcardType) {
386 return getSupertypeFromUpperBounds(superclass, ((WildcardType) runtimeType).getUpperBounds());
387 }
388 if (superclass.isArray()) {
389 return getArraySupertype(superclass);
390 }
391 @SuppressWarnings("unchecked") // resolved supertype
392 TypeToken<? super T> supertype = (TypeToken<? super T>)
393 resolveSupertype(toGenericType(superclass).runtimeType);
394 return supertype;
395 }
396
397 /**
398 * Returns subtype of {@code this} with {@code subclass} as the raw class.
399 * For example, if this is {@code Iterable<String>} and {@code subclass} is {@code List},
400 * {@code List<String>} is returned.
401 */
402 public final TypeToken<? extends T> getSubtype(Class<?> subclass) {
403 checkArgument(!(runtimeType instanceof TypeVariable),
404 "Cannot get subtype of type variable <%s>", this);
405 if (runtimeType instanceof WildcardType) {
406 return getSubtypeFromLowerBounds(subclass, ((WildcardType) runtimeType).getLowerBounds());
407 }
408 checkArgument(getRawType().isAssignableFrom(subclass),
409 "%s isn't a subclass of %s", subclass, this);
410 // unwrap array type if necessary
411 if (isArray()) {
412 return getArraySubtype(subclass);
413 }
414 @SuppressWarnings("unchecked") // guarded by the isAssignableFrom() statement above
415 TypeToken<? extends T> subtype = (TypeToken<? extends T>)
416 of(resolveTypeArgsForSubclass(subclass));
417 return subtype;
418 }
419
420 /** Returns true if this type is assignable from the given {@code type}. */
421 public final boolean isAssignableFrom(TypeToken<?> type) {
422 return isAssignableFrom(type.runtimeType);
423 }
424
425 /** Check if this type is assignable from the given {@code type}. */
426 public final boolean isAssignableFrom(Type type) {
427 return isAssignable(checkNotNull(type), runtimeType);
428 }
429
430 /**
431 * Returns true if this type is known to be an array type, such as {@code int[]}, {@code T[]},
432 * {@code <? extends Map<String, Integer>[]>} etc.
433 */
434 public final boolean isArray() {
435 return getComponentType() != null;
436 }
437
438 /**
439 * Returns the array component type if this type represents an array ({@code int[]}, {@code T[]},
440 * {@code <? extends Map<String, Integer>[]>} etc.), or else {@code null} is returned.
441 */
442 @Nullable public final TypeToken<?> getComponentType() {
443 Type componentType = Types.getComponentType(runtimeType);
444 if (componentType == null) {
445 return null;
446 }
447 return of(componentType);
448 }
449
450 /**
451 * The set of interfaces and classes that {@code T} is or is a subtype of. {@link Object} is not
452 * included in the set if this type is an interface.
453 */
454 public class TypeSet extends ForwardingSet<TypeToken<? super T>> implements Serializable {
455
456 private transient ImmutableSet<TypeToken<? super T>> types;
457
458 TypeSet() {}
459
460 /** Returns the types that are interfaces implemented by this type. */
461 public TypeSet interfaces() {
462 return new InterfaceSet(this);
463 }
464
465 /** Returns the types that are classes. */
466 public TypeSet classes() {
467 return new ClassSet();
468 }
469
470
471 @Override
472 protected Set<TypeToken<? super T>> delegate() {
473 ImmutableSet<TypeToken<? super T>> filteredTypes = types;
474 if (filteredTypes == null) {
475 // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
476 @SuppressWarnings({"unchecked", "rawtypes"})
477 ImmutableList<TypeToken<? super T>> collectedTypes = (ImmutableList)
478 TypeCollector.FOR_GENERIC_TYPE.collectTypes(TypeToken.this);
479 return (types = FluentIterable.from(collectedTypes)
480 .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
481 .toImmutableSet());
482 } else {
483 return filteredTypes;
484 }
485 }
486
487 /** Returns the raw types of the types in this set, in the same order. */
488 public Set<Class<? super T>> rawTypes() {
489 // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
490 @SuppressWarnings({"unchecked", "rawtypes"})
491 ImmutableList<Class<? super T>> collectedTypes = (ImmutableList)
492 TypeCollector.FOR_RAW_TYPE.collectTypes(getImmediateRawTypes());
493 return ImmutableSet.copyOf(collectedTypes);
494 }
495
496 private static final long serialVersionUID = 0;
497 }
498
499 private final class InterfaceSet extends TypeSet {
500
501 private transient final TypeSet allTypes;
502 private transient ImmutableSet<TypeToken<? super T>> interfaces;
503
504 InterfaceSet(TypeSet allTypes) {
505 this.allTypes = allTypes;
506 }
507
508 @Override
509 protected Set<TypeToken<? super T>> delegate() {
510 ImmutableSet<TypeToken<? super T>> result = interfaces;
511 if (result == null) {
512 return (interfaces = FluentIterable.from(allTypes)
513 .filter(TypeFilter.INTERFACE_ONLY)
514 .toImmutableSet());
515 } else {
516 return result;
517 }
518 }
519
520
521 @Override
522 public TypeSet interfaces() {
523 return this;
524 }
525
526 @Override
527 public Set<Class<? super T>> rawTypes() {
528 // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
529 @SuppressWarnings({"unchecked", "rawtypes"})
530 ImmutableList<Class<? super T>> collectedTypes = (ImmutableList)
531 TypeCollector.FOR_RAW_TYPE.collectTypes(getImmediateRawTypes());
532 return FluentIterable.from(collectedTypes)
533 .filter(new Predicate<Class<?>>() {
534 public boolean apply(Class<?> type) {
535 return type.isInterface();
536 }
537 })
538 .toImmutableSet();
539 }
540
541 @Override
542 public TypeSet classes() {
543 throw new UnsupportedOperationException("interfaces().classes() not supported.");
544 }
545
546 private Object readResolve() {
547 return getTypes().interfaces();
548 }
549
550 private static final long serialVersionUID = 0;
551 }
552
553 private final class ClassSet extends TypeSet {
554
555 private transient ImmutableSet<TypeToken<? super T>> classes;
556
557 @Override
558 protected Set<TypeToken<? super T>> delegate() {
559 ImmutableSet<TypeToken<? super T>> result = classes;
560 if (result == null) {
561 @SuppressWarnings({"unchecked", "rawtypes"})
562 ImmutableList<TypeToken<? super T>> collectedTypes = (ImmutableList)
563 TypeCollector.FOR_GENERIC_TYPE.classesOnly().collectTypes(TypeToken.this);
564 return (classes = FluentIterable.from(collectedTypes)
565 .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
566 .toImmutableSet());
567 } else {
568 return result;
569 }
570 }
571
572
573 @Override
574 public TypeSet classes() {
575 return this;
576 }
577
578 @Override
579 public Set<Class<? super T>> rawTypes() {
580 // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
581 @SuppressWarnings({"unchecked", "rawtypes"})
582 ImmutableList<Class<? super T>> collectedTypes = (ImmutableList)
583 TypeCollector.FOR_RAW_TYPE.classesOnly().collectTypes(getImmediateRawTypes());
584 return ImmutableSet.copyOf(collectedTypes);
585 }
586
587 @Override
588 public TypeSet interfaces() {
589 throw new UnsupportedOperationException("classes().interfaces() not supported.");
590 }
591
592 private Object readResolve() {
593 return getTypes().classes();
594 }
595
596 private static final long serialVersionUID = 0;
597 }
598
599 private enum TypeFilter implements Predicate<TypeToken<?>> {
600
601 IGNORE_TYPE_VARIABLE_OR_WILDCARD {
602 public boolean apply(TypeToken<?> type) {
603 return !(type.runtimeType instanceof TypeVariable
604 || type.runtimeType instanceof WildcardType);
605 }
606 },
607 INTERFACE_ONLY {
608 public boolean apply(TypeToken<?> type) {
609 return type.getRawType().isInterface();
610 }
611 }
612 }
613
614 /**
615 * Returns true if {@code o} is another {@code TypeToken} that represents the same {@link Type}.
616 */
617
618 @Override
619 public boolean equals(@Nullable Object o) {
620 if (o instanceof TypeToken) {
621 TypeToken<?> that = (TypeToken<?>) o;
622 return runtimeType.equals(that.runtimeType);
623 }
624 return false;
625 }
626
627
628 @Override
629 public int hashCode() {
630 return runtimeType.hashCode();
631 }
632
633
634 @Override
635 public String toString() {
636 return Types.toString(runtimeType);
637 }
638
639 /** Implemented to support serialization of subclasses. */
640 protected Object writeReplace() {
641 // TypeResolver just transforms the type to our own impls that are Serializable
642 // except TypeVariable.
643 return of(new TypeResolver().resolveType(runtimeType));
644 }
645
646 /**
647 * Ensures that this type token doesn't contain type variables, which can cause unchecked type
648 * errors for callers like {@link TypeToInstanceMap}.
649 */
650 final TypeToken<T> rejectTypeVariables() {
651 checkArgument(!Types.containsTypeVariable(runtimeType),
652 "%s contains a type variable and is not safe for the operation");
653 return this;
654 }
655
656 private static boolean isAssignable(Type from, Type to) {
657 if (to.equals(from)) {
658 return true;
659 }
660 if (to instanceof WildcardType) {
661 return isAssignableToWildcardType(from, (WildcardType) to);
662 }
663 // if "from" is type variable, it's assignable if any of its "extends"
664 // bounds is assignable to "to".
665 if (from instanceof TypeVariable) {
666 return isAssignableFromAny(((TypeVariable<?>) from).getBounds(), to);
667 }
668 // if "from" is wildcard, it'a assignable to "to" if any of its "extends"
669 // bounds is assignable to "to".
670 if (from instanceof WildcardType) {
671 return isAssignableFromAny(((WildcardType) from).getUpperBounds(), to);
672 }
673 if (from instanceof GenericArrayType) {
674 return isAssignableFromGenericArrayType((GenericArrayType) from, to);
675 }
676 // Proceed to regular Type assignability check
677 if (to instanceof Class) {
678 return isAssignableToClass(from, (Class<?>) to);
679 } else if (to instanceof ParameterizedType) {
680 return isAssignableToParameterizedType(from, (ParameterizedType) to);
681 } else if (to instanceof GenericArrayType) {
682 return isAssignableToGenericArrayType(from, (GenericArrayType) to);
683 } else { // to instanceof TypeVariable
684 return false;
685 }
686 }
687
688 private static boolean isAssignableFromAny(Type[] fromTypes, Type to) {
689 for (Type from : fromTypes) {
690 if (isAssignable(from, to)) {
691 return true;
692 }
693 }
694 return false;
695 }
696
697 private static boolean isAssignableToClass(Type from, Class<?> to) {
698 return to.isAssignableFrom(getRawType(from));
699 }
700
701 private static boolean isAssignableToWildcardType(
702 Type from, WildcardType to) {
703 // if "to" is <? extends Foo>, "from" can be:
704 // Foo, SubFoo, <? extends Foo>, <? extends SubFoo>, <T extends Foo> or
705 // <T extends SubFoo>.
706 // if "to" is <? super Foo>, "from" can be:
707 // Foo, SuperFoo, <? super Foo> or <? super SuperFoo>.
708 return isAssignable(from, supertypeBound(to)) && isAssignableBySubtypeBound(from, to);
709 }
710
711 private static boolean isAssignableBySubtypeBound(Type from, WildcardType to) {
712 Type toSubtypeBound = subtypeBound(to);
713 if (toSubtypeBound == null) {
714 return true;
715 }
716 Type fromSubtypeBound = subtypeBound(from);
717 if (fromSubtypeBound == null) {
718 return false;
719 }
720 return isAssignable(toSubtypeBound, fromSubtypeBound);
721 }
722
723 private static boolean isAssignableToParameterizedType(Type from, ParameterizedType to) {
724 Class<?> matchedClass = getRawType(to);
725 if (!matchedClass.isAssignableFrom(getRawType(from))) {
726 return false;
727 }
728 Type[] typeParams = matchedClass.getTypeParameters();
729 Type[] toTypeArgs = to.getActualTypeArguments();
730 TypeToken<?> fromTypeToken = of(from);
731 for (int i = 0; i < typeParams.length; i++) {
732 // If "to" is "List<? extends CharSequence>"
733 // and "from" is StringArrayList,
734 // First step is to figure out StringArrayList "is-a" List<E> and <E> is
735 // String.
736 // typeParams[0] is E and fromTypeToken.get(typeParams[0]) will resolve to
737 // String.
738 // String is then matched against <? extends CharSequence>.
739 Type fromTypeArg = fromTypeToken.resolveType(typeParams[i]).runtimeType;
740 if (!matchTypeArgument(fromTypeArg, toTypeArgs[i])) {
741 return false;
742 }
743 }
744 return true;
745 }
746
747 private static boolean isAssignableToGenericArrayType(Type from, GenericArrayType to) {
748 if (from instanceof Class) {
749 Class<?> fromClass = (Class<?>) from;
750 if (!fromClass.isArray()) {
751 return false;
752 }
753 return isAssignable(fromClass.getComponentType(), to.getGenericComponentType());
754 } else if (from instanceof GenericArrayType) {
755 GenericArrayType fromArrayType = (GenericArrayType) from;
756 return isAssignable(fromArrayType.getGenericComponentType(), to.getGenericComponentType());
757 } else {
758 return false;
759 }
760 }
761
762 private static boolean isAssignableFromGenericArrayType(GenericArrayType from, Type to) {
763 if (to instanceof Class) {
764 Class<?> toClass = (Class<?>) to;
765 if (!toClass.isArray()) {
766 return toClass == Object.class; // any T[] is assignable to Object
767 }
768 return isAssignable(from.getGenericComponentType(), toClass.getComponentType());
769 } else if (to instanceof GenericArrayType) {
770 GenericArrayType toArrayType = (GenericArrayType) to;
771 return isAssignable(from.getGenericComponentType(), toArrayType.getGenericComponentType());
772 } else {
773 return false;
774 }
775 }
776
777 private static boolean matchTypeArgument(Type from, Type to) {
778 if (from.equals(to)) {
779 return true;
780 }
781 if (to instanceof WildcardType) {
782 return isAssignableToWildcardType(from, (WildcardType) to);
783 }
784 return false;
785 }
786
787 private static Type supertypeBound(Type type) {
788 if (type instanceof WildcardType) {
789 return supertypeBound((WildcardType) type);
790 }
791 return type;
792 }
793
794 private static Type supertypeBound(WildcardType type) {
795 Type[] upperBounds = type.getUpperBounds();
796 if (upperBounds.length == 1) {
797 return supertypeBound(upperBounds[0]);
798 } else if (upperBounds.length == 0) {
799 return Object.class;
800 } else {
801 throw new AssertionError(
802 "There should be at most one upper bound for wildcard type: " + type);
803 }
804 }
805
806 @Nullable private static Type subtypeBound(Type type) {
807 if (type instanceof WildcardType) {
808 return subtypeBound((WildcardType) type);
809 } else {
810 return type;
811 }
812 }
813
814 @Nullable private static Type subtypeBound(WildcardType type) {
815 Type[] lowerBounds = type.getLowerBounds();
816 if (lowerBounds.length == 1) {
817 return subtypeBound(lowerBounds[0]);
818 } else if (lowerBounds.length == 0) {
819 return null;
820 } else {
821 throw new AssertionError(
822 "Wildcard should have at most one lower bound: " + type);
823 }
824 }
825
826 @VisibleForTesting static Class<?> getRawType(Type type) {
827 // For wildcard or type variable, the first bound determines the runtime type.
828 return getRawTypes(type).iterator().next();
829 }
830
831 @VisibleForTesting static ImmutableSet<Class<?>> getRawTypes(Type type) {
832 if (type instanceof Class) {
833 return ImmutableSet.<Class<?>>of((Class<?>) type);
834 } else if (type instanceof ParameterizedType) {
835 ParameterizedType parameterizedType = (ParameterizedType) type;
836 // JDK implementation declares getRawType() to return Class<?>
837 return ImmutableSet.<Class<?>>of((Class<?>) parameterizedType.getRawType());
838 } else if (type instanceof GenericArrayType) {
839 GenericArrayType genericArrayType = (GenericArrayType) type;
840 return ImmutableSet.<Class<?>>of(Types.getArrayClass(
841 getRawType(genericArrayType.getGenericComponentType())));
842 } else if (type instanceof TypeVariable) {
843 return getRawTypes(((TypeVariable<?>) type).getBounds());
844 } else if (type instanceof WildcardType) {
845 return getRawTypes(((WildcardType) type).getUpperBounds());
846 } else {
847 throw new AssertionError(type + " unsupported");
848 }
849 }
850
851 private static ImmutableSet<Class<?>> getRawTypes(Type[] types) {
852 ImmutableSet.Builder<Class<?>> builder = ImmutableSet.builder();
853 for (Type type : types) {
854 builder.addAll(getRawTypes(type));
855 }
856 return builder.build();
857 }
858
859 /**
860 * Returns the type token representing the generic type declaration of {@code cls}. For example:
861 * {@code TypeToken.getGenericType(Iterable.class)} returns {@code Iterable<T>}.
862 *
863 * <p>If {@code cls} isn't parameterized and isn't a generic array, the type token of the class is
864 * returned.
865 */
866 @VisibleForTesting static <T> TypeToken<? extends T> toGenericType(Class<T> cls) {
867 if (cls.isArray()) {
868 Type arrayOfGenericType = Types.newArrayType(
869 // If we are passed with int[].class, don't turn it to GenericArrayType
870 toGenericType(cls.getComponentType()).runtimeType);
871 @SuppressWarnings("unchecked") // array is covariant
872 TypeToken<? extends T> result = (TypeToken<? extends T>) of(arrayOfGenericType);
873 return result;
874 }
875 TypeVariable<Class<T>>[] typeParams = cls.getTypeParameters();
876 if (typeParams.length > 0) {
877 @SuppressWarnings("unchecked") // Like, it's Iterable<T> for Iterable.class
878 TypeToken<? extends T> type = (TypeToken<? extends T>)
879 of(Types.newParameterizedType(cls, typeParams));
880 return type;
881 } else {
882 return of(cls);
883 }
884 }
885
886 private TypeToken<? super T> getSupertypeFromUpperBounds(
887 Class<? super T> supertype, Type[] upperBounds) {
888 for (Type upperBound : upperBounds) {
889 @SuppressWarnings("unchecked") // T's upperbound is <? super T>.
890 TypeToken<? super T> bound = (TypeToken<? super T>) of(upperBound);
891 if (of(supertype).isAssignableFrom(bound)) {
892 @SuppressWarnings({"rawtypes", "unchecked"}) // guarded by the isAssignableFrom check.
893 TypeToken<? super T> result = bound.getSupertype((Class) supertype);
894 return result;
895 }
896 }
897 throw new IllegalArgumentException(supertype + " isn't a super type of " + this);
898 }
899
900 private TypeToken<? extends T> getSubtypeFromLowerBounds(Class<?> subclass, Type[] lowerBounds) {
901 for (Type lowerBound : lowerBounds) {
902 @SuppressWarnings("unchecked") // T's lower bound is <? extends T>
903 TypeToken<? extends T> bound = (TypeToken<? extends T>) of(lowerBound);
904 // Java supports only one lowerbound anyway.
905 return bound.getSubtype(subclass);
906 }
907 throw new IllegalArgumentException(subclass + " isn't a subclass of " + this);
908 }
909
910 private TypeToken<? super T> getArraySupertype(Class<? super T> supertype) {
911 // with component type, we have lost generic type information
912 // Use raw type so that compiler allows us to call getSupertype()
913 @SuppressWarnings("rawtypes")
914 TypeToken componentType = checkNotNull(getComponentType(),
915 "%s isn't a super type of %s", supertype, this);
916 // array is covariant. component type is super type, so is the array type.
917 @SuppressWarnings("unchecked") // going from raw type back to generics
918 TypeToken<?> componentSupertype = componentType.getSupertype(supertype.getComponentType());
919 @SuppressWarnings("unchecked") // component type is super type, so is array type.
920 TypeToken<? super T> result = (TypeToken<? super T>)
921 // If we are passed with int[].class, don't turn it to GenericArrayType
922 of(newArrayClassOrGenericArrayType(componentSupertype.runtimeType));
923 return result;
924 }
925
926 private TypeToken<? extends T> getArraySubtype(Class<?> subclass) {
927 // array is covariant. component type is subtype, so is the array type.
928 TypeToken<?> componentSubtype = getComponentType()
929 .getSubtype(subclass.getComponentType());
930 @SuppressWarnings("unchecked") // component type is subtype, so is array type.
931 TypeToken<? extends T> result = (TypeToken<? extends T>)
932 // If we are passed with int[].class, don't turn it to GenericArrayType
933 of(newArrayClassOrGenericArrayType(componentSubtype.runtimeType));
934 return result;
935 }
936
937 private Type resolveTypeArgsForSubclass(Class<?> subclass) {
938 if (runtimeType instanceof Class) {
939 // no resolution needed
940 return subclass;
941 }
942 // class Base<A, B> {}
943 // class Sub<X, Y> extends Base<X, Y> {}
944 // Base<String, Integer>.subtype(Sub.class):
945
946 // Sub<X, Y>.getSupertype(Base.class) => Base<X, Y>
947 // => X=String, Y=Integer
948 // => Sub<X, Y>=Sub<String, Integer>
949 TypeToken<?> genericSubtype = toGenericType(subclass);
950 @SuppressWarnings({"rawtypes", "unchecked"}) // subclass isn't <? extends T>
951 Type supertypeWithArgsFromSubtype = genericSubtype
952 .getSupertype((Class) getRawType())
953 .runtimeType;
954 return new TypeResolver().where(supertypeWithArgsFromSubtype, runtimeType)
955 .resolveType(genericSubtype.runtimeType);
956 }
957
958 /**
959 * Creates an array class if {@code componentType} is a class, or else, a
960 * {@link GenericArrayType}. This is what Java7 does for generic array type
961 * parameters.
962 */
963 private static Type newArrayClassOrGenericArrayType(Type componentType) {
964 return Types.JavaVersion.JAVA7.newArrayType(componentType);
965 }
966
967 private static final class SimpleTypeToken<T> extends TypeToken<T> {
968
969 SimpleTypeToken(Type type) {
970 super(type);
971 }
972
973 private static final long serialVersionUID = 0;
974 }
975
976 /**
977 * Collects parent types from a sub type.
978 *
979 * @param <K> The type "kind". Either a TypeToken, or Class.
980 */
981 private abstract static class TypeCollector<K> {
982
983 static final TypeCollector<TypeToken<?>> FOR_GENERIC_TYPE =
984 new TypeCollector<TypeToken<?>>() {
985 @Override
986 Class<?> getRawType(TypeToken<?> type) {
987 return type.getRawType();
988 }
989
990 @Override
991 Iterable<? extends TypeToken<?>> getInterfaces(TypeToken<?> type) {
992 return type.getGenericInterfaces();
993 }
994
995 @Override
996 @Nullable
997 TypeToken<?> getSuperclass(TypeToken<?> type) {
998 return type.getGenericSuperclass();
999 }
1000 };
1001
1002 static final TypeCollector<Class<?>> FOR_RAW_TYPE =
1003 new TypeCollector<Class<?>>() {
1004 @Override
1005 Class<?> getRawType(Class<?> type) {
1006 return type;
1007 }
1008
1009 @Override
1010 Iterable<? extends Class<?>> getInterfaces(Class<?> type) {
1011 return (Iterable<? extends Class<?>>) Arrays.asList(type.getInterfaces());
1012 }
1013
1014 @Override
1015 @Nullable
1016 Class<?> getSuperclass(Class<?> type) {
1017 return type.getSuperclass();
1018 }
1019 };
1020
1021 /** For just classes, we don't have to traverse interfaces. */
1022 final TypeCollector<K> classesOnly() {
1023 return new ForwardingTypeCollector<K>(this) {
1024 @Override
1025 Iterable<? extends K> getInterfaces(K type) {
1026 return ImmutableSet.of();
1027 }
1028 @Override
1029 ImmutableList<K> collectTypes(Iterable<? extends K> types) {
1030 ImmutableList.Builder<K> builder = ImmutableList.builder();
1031 for (K type : types) {
1032 if (!getRawType(type).isInterface()) {
1033 builder.add(type);
1034 }
1035 }
1036 return super.collectTypes(builder.build());
1037 }
1038 };
1039 }
1040
1041 final ImmutableList<K> collectTypes(K type) {
1042 return collectTypes(ImmutableList.of(type));
1043 }
1044
1045 ImmutableList<K> collectTypes(Iterable<? extends K> types) {
1046 // type -> order number. 1 for Object, 2 for anything directly below, so on so forth.
1047 Map<K, Integer> map = Maps.newHashMap();
1048 for (K type : types) {
1049 collectTypes(type, map);
1050 }
1051 return sortKeysByValue(map, Ordering.natural().reverse());
1052 }
1053
1054 /** Collects all types to map, and returns the total depth from T up to Object. */
1055 private int collectTypes(K type, Map<? super K, Integer> map) {
1056 Integer existing = map.get(this);
1057 if (existing != null) {
1058 // short circuit: if set contains type it already contains its supertypes
1059 return existing;
1060 }
1061 int aboveMe = getRawType(type).isInterface()
1062 ? 1 // interfaces should be listed before Object
1063 : 0;
1064 for (K interfaceType : getInterfaces(type)) {
1065 aboveMe = Math.max(aboveMe, collectTypes(interfaceType, map));
1066 }
1067 K superclass = getSuperclass(type);
1068 if (superclass != null) {
1069 aboveMe = Math.max(aboveMe, collectTypes(superclass, map));
1070 }
1071 // TODO(benyu): should we include Object for interface?
1072 // Also, CharSequence[] and Object[] for String[]?
1073 map.put(type, aboveMe + 1);
1074 return aboveMe + 1;
1075 }
1076
1077 private static <K, V> ImmutableList<K> sortKeysByValue(
1078 final Map<K, V> map, final Comparator<? super V> valueComparator) {
1079 Ordering<K> keyOrdering = new Ordering<K>() {
1080 @Override
1081 public int compare(K left, K right) {
1082 return valueComparator.compare(map.get(left), map.get(right));
1083 }
1084 };
1085 return keyOrdering.immutableSortedCopy(map.keySet());
1086 }
1087
1088 abstract Class<?> getRawType(K type);
1089 abstract Iterable<? extends K> getInterfaces(K type);
1090 @Nullable abstract K getSuperclass(K type);
1091
1092 private static class ForwardingTypeCollector<K> extends TypeCollector<K> {
1093
1094 private final TypeCollector<K> delegate;
1095
1096 ForwardingTypeCollector(TypeCollector<K> delegate) {
1097 this.delegate = delegate;
1098 }
1099
1100 @Override
1101 Class<?> getRawType(K type) {
1102 return delegate.getRawType(type);
1103 }
1104
1105 @Override
1106 Iterable<? extends K> getInterfaces(K type) {
1107 return delegate.getInterfaces(type);
1108 }
1109
1110 @Override
1111 K getSuperclass(K type) {
1112 return delegate.getSuperclass(type);
1113 }
1114 }
1115 }
1116 }