001/*
002 * Copyright (C) 2006 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.reflect;
016
017import static com.google.common.base.Preconditions.checkArgument;
018import static com.google.common.base.Preconditions.checkNotNull;
019import static com.google.common.base.Preconditions.checkState;
020
021import com.google.common.annotations.Beta;
022import com.google.common.annotations.VisibleForTesting;
023import com.google.common.base.Joiner;
024import com.google.common.base.Predicate;
025import com.google.common.collect.FluentIterable;
026import com.google.common.collect.ForwardingSet;
027import com.google.common.collect.ImmutableList;
028import com.google.common.collect.ImmutableMap;
029import com.google.common.collect.ImmutableSet;
030import com.google.common.collect.Maps;
031import com.google.common.collect.Ordering;
032import com.google.common.primitives.Primitives;
033import com.google.errorprone.annotations.CanIgnoreReturnValue;
034import java.io.Serializable;
035import java.lang.reflect.Constructor;
036import java.lang.reflect.GenericArrayType;
037import java.lang.reflect.Method;
038import java.lang.reflect.Modifier;
039import java.lang.reflect.ParameterizedType;
040import java.lang.reflect.Type;
041import java.lang.reflect.TypeVariable;
042import java.lang.reflect.WildcardType;
043import java.util.ArrayList;
044import java.util.Arrays;
045import java.util.Comparator;
046import java.util.List;
047import java.util.Map;
048import java.util.Set;
049import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
050import org.checkerframework.checker.nullness.qual.Nullable;
051
052/**
053 * A {@link Type} with generics.
054 *
055 * <p>Operations that are otherwise only available in {@link Class} are implemented to support
056 * {@code Type}, for example {@link #isSubtypeOf}, {@link #isArray} and {@link #getComponentType}.
057 * It also provides additional utilities such as {@link #getTypes}, {@link #resolveType}, etc.
058 *
059 * <p>There are three ways to get a {@code TypeToken} instance:
060 *
061 * <ul>
062 *   <li>Wrap a {@code Type} obtained via reflection. For example: {@code
063 *       TypeToken.of(method.getGenericReturnType())}.
064 *   <li>Capture a generic type with a (usually anonymous) subclass. For example:
065 *       <pre>{@code
066 * new TypeToken<List<String>>() {}
067 * }</pre>
068 *       <p>Note that it's critical that the actual type argument is carried by a subclass. The
069 *       following code is wrong because it only captures the {@code <T>} type variable of the
070 *       {@code listType()} method signature; while {@code <String>} is lost in erasure:
071 *       <pre>{@code
072 * class Util {
073 *   static <T> TypeToken<List<T>> listType() {
074 *     return new TypeToken<List<T>>() {};
075 *   }
076 * }
077 *
078 * TypeToken<List<String>> stringListType = Util.<String>listType();
079 * }</pre>
080 *   <li>Capture a generic type with a (usually anonymous) subclass and resolve it against a context
081 *       class that knows what the type parameters are. For example:
082 *       <pre>{@code
083 * abstract class IKnowMyType<T> {
084 *   TypeToken<T> type = new TypeToken<T>(getClass()) {};
085 * }
086 * new IKnowMyType<String>() {}.type => String
087 * }</pre>
088 * </ul>
089 *
090 * <p>{@code TypeToken} is serializable when no type variable is contained in the type.
091 *
092 * <p>Note to Guice users: {@code} TypeToken is similar to Guice's {@code TypeLiteral} class except
093 * that it is serializable and offers numerous additional utility methods.
094 *
095 * @author Bob Lee
096 * @author Sven Mawson
097 * @author Ben Yu
098 * @since 12.0
099 */
100@Beta
101@SuppressWarnings("serial") // SimpleTypeToken is the serialized form.
102public abstract class TypeToken<T> extends TypeCapture<T> implements Serializable {
103
104  private final Type runtimeType;
105
106  /** Resolver for resolving parameter and field types with {@link #runtimeType} as context. */
107  private transient @MonotonicNonNull TypeResolver invariantTypeResolver;
108
109  /** Resolver for resolving covariant types with {@link #runtimeType} as context. */
110  private transient @MonotonicNonNull TypeResolver covariantTypeResolver;
111
112  /**
113   * Constructs a new type token of {@code T}.
114   *
115   * <p>Clients create an empty anonymous subclass. Doing so embeds the type parameter in the
116   * anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.
117   *
118   * <p>For example:
119   *
120   * <pre>{@code
121   * TypeToken<List<String>> t = new TypeToken<List<String>>() {};
122   * }</pre>
123   */
124  protected TypeToken() {
125    this.runtimeType = capture();
126    checkState(
127        !(runtimeType instanceof TypeVariable),
128        "Cannot construct a TypeToken for a type variable.\n"
129            + "You probably meant to call new TypeToken<%s>(getClass()) "
130            + "that can resolve the type variable for you.\n"
131            + "If you do need to create a TypeToken of a type variable, "
132            + "please use TypeToken.of() instead.",
133        runtimeType);
134  }
135
136  /**
137   * Constructs a new type token of {@code T} while resolving free type variables in the context of
138   * {@code declaringClass}.
139   *
140   * <p>Clients create an empty anonymous subclass. Doing so embeds the type parameter in the
141   * anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure.
142   *
143   * <p>For example:
144   *
145   * <pre>{@code
146   * abstract class IKnowMyType<T> {
147   *   TypeToken<T> getMyType() {
148   *     return new TypeToken<T>(getClass()) {};
149   *   }
150   * }
151   *
152   * new IKnowMyType<String>() {}.getMyType() => String
153   * }</pre>
154   */
155  protected TypeToken(Class<?> declaringClass) {
156    Type captured = super.capture();
157    if (captured instanceof Class) {
158      this.runtimeType = captured;
159    } else {
160      this.runtimeType = TypeResolver.covariantly(declaringClass).resolveType(captured);
161    }
162  }
163
164  private TypeToken(Type type) {
165    this.runtimeType = checkNotNull(type);
166  }
167
168  /** Returns an instance of type token that wraps {@code type}. */
169  public static <T> TypeToken<T> of(Class<T> type) {
170    return new SimpleTypeToken<T>(type);
171  }
172
173  /** Returns an instance of type token that wraps {@code type}. */
174  public static TypeToken<?> of(Type type) {
175    return new SimpleTypeToken<>(type);
176  }
177
178  /**
179   * Returns the raw type of {@code T}. Formally speaking, if {@code T} is returned by {@link
180   * java.lang.reflect.Method#getGenericReturnType}, the raw type is what's returned by {@link
181   * java.lang.reflect.Method#getReturnType} of the same method object. Specifically:
182   *
183   * <ul>
184   *   <li>If {@code T} is a {@code Class} itself, {@code T} itself is returned.
185   *   <li>If {@code T} is a {@link ParameterizedType}, the raw type of the parameterized type is
186   *       returned.
187   *   <li>If {@code T} is a {@link GenericArrayType}, the returned type is the corresponding array
188   *       class. For example: {@code List<Integer>[] => List[]}.
189   *   <li>If {@code T} is a type variable or a wildcard type, the raw type of the first upper bound
190   *       is returned. For example: {@code <X extends Foo> => Foo}.
191   * </ul>
192   */
193  public final Class<? super T> getRawType() {
194    // For wildcard or type variable, the first bound determines the runtime type.
195    Class<?> rawType = getRawTypes().iterator().next();
196    @SuppressWarnings("unchecked") // raw type is |T|
197    Class<? super T> result = (Class<? super T>) rawType;
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} are
208   * substituted by {@code typeArg}. For example, it can be used to construct {@code Map<K, V>} for
209   * any {@code K} and {@code V} type:
210   *
211   * <pre>{@code
212   * static <K, V> TypeToken<Map<K, V>> mapOf(
213   *     TypeToken<K> keyType, TypeToken<V> valueType) {
214   *   return new TypeToken<Map<K, V>>() {}
215   *       .where(new TypeParameter<K>() {}, keyType)
216   *       .where(new TypeParameter<V>() {}, valueType);
217   * }
218   * }</pre>
219   *
220   * @param <X> The parameter type
221   * @param typeParam the parameter type variable
222   * @param typeArg the actual type to substitute
223   */
224  public final <X> TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg) {
225    TypeResolver resolver =
226        new TypeResolver()
227            .where(
228                ImmutableMap.of(
229                    new TypeResolver.TypeVariableKey(typeParam.typeVariable), typeArg.runtimeType));
230    // If there's any type error, we'd report now rather than later.
231    return new SimpleTypeToken<T>(resolver.resolveType(runtimeType));
232  }
233
234  /**
235   * Returns a new {@code TypeToken} where type variables represented by {@code typeParam} are
236   * substituted by {@code typeArg}. For example, it can be used to construct {@code Map<K, V>} for
237   * any {@code K} and {@code V} type:
238   *
239   * <pre>{@code
240   * static <K, V> TypeToken<Map<K, V>> mapOf(
241   *     Class<K> keyType, Class<V> valueType) {
242   *   return new TypeToken<Map<K, V>>() {}
243   *       .where(new TypeParameter<K>() {}, keyType)
244   *       .where(new TypeParameter<V>() {}, valueType);
245   * }
246   * }</pre>
247   *
248   * @param <X> The parameter type
249   * @param typeParam the parameter type variable
250   * @param typeArg the actual type to substitute
251   */
252  public final <X> TypeToken<T> where(TypeParameter<X> typeParam, Class<X> typeArg) {
253    return where(typeParam, of(typeArg));
254  }
255
256  /**
257   * Resolves the given {@code type} against the type context represented by this type. For example:
258   *
259   * <pre>{@code
260   * new TypeToken<List<String>>() {}.resolveType(
261   *     List.class.getMethod("get", int.class).getGenericReturnType())
262   * => String.class
263   * }</pre>
264   */
265  public final TypeToken<?> resolveType(Type type) {
266    checkNotNull(type);
267    // Being conservative here because the user could use resolveType() to resolve a type in an
268    // invariant context.
269    return of(getInvariantTypeResolver().resolveType(type));
270  }
271
272  private TypeToken<?> resolveSupertype(Type type) {
273    TypeToken<?> supertype = of(getCovariantTypeResolver().resolveType(type));
274    // super types' type mapping is a subset of type mapping of this type.
275    supertype.covariantTypeResolver = covariantTypeResolver;
276    supertype.invariantTypeResolver = invariantTypeResolver;
277    return supertype;
278  }
279
280  /**
281   * Returns the generic superclass of this type or {@code null} if the type represents {@link
282   * Object} or an interface. This method is similar but different from {@link
283   * Class#getGenericSuperclass}. For example, {@code new TypeToken<StringArrayList>()
284   * {}.getGenericSuperclass()} will return {@code new TypeToken<ArrayList<String>>() {}}; while
285   * {@code StringArrayList.class.getGenericSuperclass()} will return {@code ArrayList<E>}, where
286   * {@code E} is the type variable declared by class {@code ArrayList}.
287   *
288   * <p>If this type is a type variable or wildcard, its first upper bound is examined and returned
289   * if the bound is a class or extends from a class. This means that the returned type could be a
290   * type variable too.
291   */
292  final @Nullable TypeToken<? super T> getGenericSuperclass() {
293    if (runtimeType instanceof TypeVariable) {
294      // First bound is always the super class, if one exists.
295      return boundAsSuperclass(((TypeVariable<?>) runtimeType).getBounds()[0]);
296    }
297    if (runtimeType instanceof WildcardType) {
298      // wildcard has one and only one upper bound.
299      return boundAsSuperclass(((WildcardType) runtimeType).getUpperBounds()[0]);
300    }
301    Type superclass = getRawType().getGenericSuperclass();
302    if (superclass == null) {
303      return null;
304    }
305    @SuppressWarnings("unchecked") // super class of T
306    TypeToken<? super T> superToken = (TypeToken<? super T>) resolveSupertype(superclass);
307    return superToken;
308  }
309
310  private @Nullable TypeToken<? super T> boundAsSuperclass(Type bound) {
311    TypeToken<?> token = of(bound);
312    if (token.getRawType().isInterface()) {
313      return null;
314    }
315    @SuppressWarnings("unchecked") // only upper bound of T is passed in.
316    TypeToken<? super T> superclass = (TypeToken<? super T>) token;
317    return superclass;
318  }
319
320  /**
321   * Returns the generic interfaces that this type directly {@code implements}. This method is
322   * similar but different from {@link Class#getGenericInterfaces()}. For example, {@code new
323   * TypeToken<List<String>>() {}.getGenericInterfaces()} will return a list that contains {@code
324   * new TypeToken<Iterable<String>>() {}}; while {@code List.class.getGenericInterfaces()} will
325   * return an array that contains {@code Iterable<T>}, where the {@code T} is the type variable
326   * declared by interface {@code Iterable}.
327   *
328   * <p>If this type is a type variable or wildcard, its upper bounds are examined and those that
329   * are either an interface or upper-bounded only by interfaces are returned. This means that the
330   * returned types could include type variables too.
331   */
332  final ImmutableList<TypeToken<? super T>> getGenericInterfaces() {
333    if (runtimeType instanceof TypeVariable) {
334      return boundsAsInterfaces(((TypeVariable<?>) runtimeType).getBounds());
335    }
336    if (runtimeType instanceof WildcardType) {
337      return boundsAsInterfaces(((WildcardType) runtimeType).getUpperBounds());
338    }
339    ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
340    for (Type interfaceType : getRawType().getGenericInterfaces()) {
341      @SuppressWarnings("unchecked") // interface of T
342      TypeToken<? super T> resolvedInterface =
343          (TypeToken<? super T>) resolveSupertype(interfaceType);
344      builder.add(resolvedInterface);
345    }
346    return builder.build();
347  }
348
349  private ImmutableList<TypeToken<? super T>> boundsAsInterfaces(Type[] bounds) {
350    ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder();
351    for (Type bound : bounds) {
352      @SuppressWarnings("unchecked") // upper bound of T
353      TypeToken<? super T> boundType = (TypeToken<? super T>) of(bound);
354      if (boundType.getRawType().isInterface()) {
355        builder.add(boundType);
356      }
357    }
358    return builder.build();
359  }
360
361  /**
362   * Returns the set of interfaces and classes that this type is or is a subtype of. The returned
363   * types are parameterized with proper type arguments.
364   *
365   * <p>Subtypes are always listed before supertypes. But the reverse is not true. A type isn't
366   * necessarily a subtype of all the types following. Order between types without subtype
367   * relationship is arbitrary and not guaranteed.
368   *
369   * <p>If this type is a type variable or wildcard, upper bounds that are themselves type variables
370   * aren't included (their super interfaces and superclasses are).
371   */
372  public final TypeSet getTypes() {
373    return new TypeSet();
374  }
375
376  /**
377   * Returns the generic form of {@code superclass}. For example, if this is {@code
378   * ArrayList<String>}, {@code Iterable<String>} is returned given the input {@code
379   * Iterable.class}.
380   */
381  public final TypeToken<? super T> getSupertype(Class<? super T> superclass) {
382    checkArgument(
383        this.someRawTypeIsSubclassOf(superclass),
384        "%s is not a super class of %s",
385        superclass,
386        this);
387    if (runtimeType instanceof TypeVariable) {
388      return getSupertypeFromUpperBounds(superclass, ((TypeVariable<?>) runtimeType).getBounds());
389    }
390    if (runtimeType instanceof WildcardType) {
391      return getSupertypeFromUpperBounds(superclass, ((WildcardType) runtimeType).getUpperBounds());
392    }
393    if (superclass.isArray()) {
394      return getArraySupertype(superclass);
395    }
396    @SuppressWarnings("unchecked") // resolved supertype
397    TypeToken<? super T> supertype =
398        (TypeToken<? super T>) resolveSupertype(toGenericType(superclass).runtimeType);
399    return supertype;
400  }
401
402  /**
403   * Returns subtype of {@code this} with {@code subclass} as the raw class. For example, if this is
404   * {@code Iterable<String>} and {@code subclass} is {@code List}, {@code List<String>} is
405   * returned.
406   */
407  public final TypeToken<? extends T> getSubtype(Class<?> subclass) {
408    checkArgument(
409        !(runtimeType instanceof TypeVariable), "Cannot get subtype of type variable <%s>", this);
410    if (runtimeType instanceof WildcardType) {
411      return getSubtypeFromLowerBounds(subclass, ((WildcardType) runtimeType).getLowerBounds());
412    }
413    // unwrap array type if necessary
414    if (isArray()) {
415      return getArraySubtype(subclass);
416    }
417    // At this point, it's either a raw class or parameterized type.
418    checkArgument(
419        getRawType().isAssignableFrom(subclass), "%s isn't a subclass of %s", subclass, this);
420    Type resolvedTypeArgs = resolveTypeArgsForSubclass(subclass);
421    @SuppressWarnings("unchecked") // guarded by the isAssignableFrom() statement above
422    TypeToken<? extends T> subtype = (TypeToken<? extends T>) of(resolvedTypeArgs);
423    checkArgument(
424        subtype.isSubtypeOf(this), "%s does not appear to be a subtype of %s", subtype, this);
425    return subtype;
426  }
427
428  /**
429   * Returns true if this type is a supertype of the given {@code type}. "Supertype" is defined
430   * according to <a
431   * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type
432   * arguments</a> introduced with Java generics.
433   *
434   * @since 19.0
435   */
436  public final boolean isSupertypeOf(TypeToken<?> type) {
437    return type.isSubtypeOf(getType());
438  }
439
440  /**
441   * Returns true if this type is a supertype of the given {@code type}. "Supertype" is defined
442   * according to <a
443   * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type
444   * arguments</a> introduced with Java generics.
445   *
446   * @since 19.0
447   */
448  public final boolean isSupertypeOf(Type type) {
449    return of(type).isSubtypeOf(getType());
450  }
451
452  /**
453   * Returns true if this type is a subtype of the given {@code type}. "Subtype" is defined
454   * according to <a
455   * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type
456   * arguments</a> introduced with Java generics.
457   *
458   * @since 19.0
459   */
460  public final boolean isSubtypeOf(TypeToken<?> type) {
461    return isSubtypeOf(type.getType());
462  }
463
464  /**
465   * Returns true if this type is a subtype of the given {@code type}. "Subtype" is defined
466   * according to <a
467   * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type
468   * arguments</a> introduced with Java generics.
469   *
470   * @since 19.0
471   */
472  public final boolean isSubtypeOf(Type supertype) {
473    checkNotNull(supertype);
474    if (supertype instanceof WildcardType) {
475      // if 'supertype' is <? super Foo>, 'this' can be:
476      // Foo, SubFoo, <? extends Foo>.
477      // if 'supertype' is <? extends Foo>, nothing is a subtype.
478      return any(((WildcardType) supertype).getLowerBounds()).isSupertypeOf(runtimeType);
479    }
480    // if 'this' is wildcard, it's a suptype of to 'supertype' if any of its "extends"
481    // bounds is a subtype of 'supertype'.
482    if (runtimeType instanceof WildcardType) {
483      // <? super Base> is of no use in checking 'from' being a subtype of 'to'.
484      return any(((WildcardType) runtimeType).getUpperBounds()).isSubtypeOf(supertype);
485    }
486    // if 'this' is type variable, it's a subtype if any of its "extends"
487    // bounds is a subtype of 'supertype'.
488    if (runtimeType instanceof TypeVariable) {
489      return runtimeType.equals(supertype)
490          || any(((TypeVariable<?>) runtimeType).getBounds()).isSubtypeOf(supertype);
491    }
492    if (runtimeType instanceof GenericArrayType) {
493      return of(supertype).isSupertypeOfArray((GenericArrayType) runtimeType);
494    }
495    // Proceed to regular Type subtype check
496    if (supertype instanceof Class) {
497      return this.someRawTypeIsSubclassOf((Class<?>) supertype);
498    } else if (supertype instanceof ParameterizedType) {
499      return this.isSubtypeOfParameterizedType((ParameterizedType) supertype);
500    } else if (supertype instanceof GenericArrayType) {
501      return this.isSubtypeOfArrayType((GenericArrayType) supertype);
502    } else { // to instanceof TypeVariable
503      return false;
504    }
505  }
506
507  /**
508   * Returns true if this type is known to be an array type, such as {@code int[]}, {@code T[]},
509   * {@code <? extends Map<String, Integer>[]>} etc.
510   */
511  public final boolean isArray() {
512    return getComponentType() != null;
513  }
514
515  /**
516   * Returns true if this type is one of the nine primitive types (including {@code void}).
517   *
518   * @since 15.0
519   */
520  public final boolean isPrimitive() {
521    return (runtimeType instanceof Class) && ((Class<?>) runtimeType).isPrimitive();
522  }
523
524  /**
525   * Returns the corresponding wrapper type if this is a primitive type; otherwise returns {@code
526   * this} itself. Idempotent.
527   *
528   * @since 15.0
529   */
530  public final TypeToken<T> wrap() {
531    if (isPrimitive()) {
532      @SuppressWarnings("unchecked") // this is a primitive class
533      Class<T> type = (Class<T>) runtimeType;
534      return of(Primitives.wrap(type));
535    }
536    return this;
537  }
538
539  private boolean isWrapper() {
540    return Primitives.allWrapperTypes().contains(runtimeType);
541  }
542
543  /**
544   * Returns the corresponding primitive type if this is a wrapper type; otherwise returns {@code
545   * this} itself. Idempotent.
546   *
547   * @since 15.0
548   */
549  public final TypeToken<T> unwrap() {
550    if (isWrapper()) {
551      @SuppressWarnings("unchecked") // this is a wrapper class
552      Class<T> type = (Class<T>) runtimeType;
553      return of(Primitives.unwrap(type));
554    }
555    return this;
556  }
557
558  /**
559   * Returns the array component type if this type represents an array ({@code int[]}, {@code T[]},
560   * {@code <? extends Map<String, Integer>[]>} etc.), or else {@code null} is returned.
561   */
562  public final @Nullable TypeToken<?> getComponentType() {
563    Type componentType = Types.getComponentType(runtimeType);
564    if (componentType == null) {
565      return null;
566    }
567    return of(componentType);
568  }
569
570  /**
571   * Returns the {@link Invokable} for {@code method}, which must be a member of {@code T}.
572   *
573   * @since 14.0
574   */
575  public final Invokable<T, Object> method(Method method) {
576    checkArgument(
577        this.someRawTypeIsSubclassOf(method.getDeclaringClass()),
578        "%s not declared by %s",
579        method,
580        this);
581    return new Invokable.MethodInvokable<T>(method) {
582      @Override
583      Type getGenericReturnType() {
584        return getCovariantTypeResolver().resolveType(super.getGenericReturnType());
585      }
586
587      @Override
588      Type[] getGenericParameterTypes() {
589        return getInvariantTypeResolver().resolveTypesInPlace(super.getGenericParameterTypes());
590      }
591
592      @Override
593      Type[] getGenericExceptionTypes() {
594        return getCovariantTypeResolver().resolveTypesInPlace(super.getGenericExceptionTypes());
595      }
596
597      @Override
598      public TypeToken<T> getOwnerType() {
599        return TypeToken.this;
600      }
601
602      @Override
603      public String toString() {
604        return getOwnerType() + "." + super.toString();
605      }
606    };
607  }
608
609  /**
610   * Returns the {@link Invokable} for {@code constructor}, which must be a member of {@code T}.
611   *
612   * @since 14.0
613   */
614  public final Invokable<T, T> constructor(Constructor<?> constructor) {
615    checkArgument(
616        constructor.getDeclaringClass() == getRawType(),
617        "%s not declared by %s",
618        constructor,
619        getRawType());
620    return new Invokable.ConstructorInvokable<T>(constructor) {
621      @Override
622      Type getGenericReturnType() {
623        return getCovariantTypeResolver().resolveType(super.getGenericReturnType());
624      }
625
626      @Override
627      Type[] getGenericParameterTypes() {
628        return getInvariantTypeResolver().resolveTypesInPlace(super.getGenericParameterTypes());
629      }
630
631      @Override
632      Type[] getGenericExceptionTypes() {
633        return getCovariantTypeResolver().resolveTypesInPlace(super.getGenericExceptionTypes());
634      }
635
636      @Override
637      public TypeToken<T> getOwnerType() {
638        return TypeToken.this;
639      }
640
641      @Override
642      public String toString() {
643        return getOwnerType() + "(" + Joiner.on(", ").join(getGenericParameterTypes()) + ")";
644      }
645    };
646  }
647
648  /**
649   * The set of interfaces and classes that {@code T} is or is a subtype of. {@link Object} is not
650   * included in the set if this type is an interface.
651   *
652   * @since 13.0
653   */
654  public class TypeSet extends ForwardingSet<TypeToken<? super T>> implements Serializable {
655
656    private transient @MonotonicNonNull ImmutableSet<TypeToken<? super T>> types;
657
658    TypeSet() {}
659
660    /** Returns the types that are interfaces implemented by this type. */
661    public TypeSet interfaces() {
662      return new InterfaceSet(this);
663    }
664
665    /** Returns the types that are classes. */
666    public TypeSet classes() {
667      return new ClassSet();
668    }
669
670    @Override
671    protected Set<TypeToken<? super T>> delegate() {
672      ImmutableSet<TypeToken<? super T>> filteredTypes = types;
673      if (filteredTypes == null) {
674        // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
675        @SuppressWarnings({"unchecked", "rawtypes"})
676        ImmutableList<TypeToken<? super T>> collectedTypes =
677            (ImmutableList) TypeCollector.FOR_GENERIC_TYPE.collectTypes(TypeToken.this);
678        return (types =
679            FluentIterable.from(collectedTypes)
680                .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
681                .toSet());
682      } else {
683        return filteredTypes;
684      }
685    }
686
687    /** Returns the raw types of the types in this set, in the same order. */
688    public Set<Class<? super T>> rawTypes() {
689      // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
690      @SuppressWarnings({"unchecked", "rawtypes"})
691      ImmutableList<Class<? super T>> collectedTypes =
692          (ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getRawTypes());
693      return ImmutableSet.copyOf(collectedTypes);
694    }
695
696    private static final long serialVersionUID = 0;
697  }
698
699  private final class InterfaceSet extends TypeSet {
700
701    private final transient TypeSet allTypes;
702    private transient @MonotonicNonNull ImmutableSet<TypeToken<? super T>> interfaces;
703
704    InterfaceSet(TypeSet allTypes) {
705      this.allTypes = allTypes;
706    }
707
708    @Override
709    protected Set<TypeToken<? super T>> delegate() {
710      ImmutableSet<TypeToken<? super T>> result = interfaces;
711      if (result == null) {
712        return (interfaces =
713            FluentIterable.from(allTypes).filter(TypeFilter.INTERFACE_ONLY).toSet());
714      } else {
715        return result;
716      }
717    }
718
719    @Override
720    public TypeSet interfaces() {
721      return this;
722    }
723
724    @Override
725    public Set<Class<? super T>> rawTypes() {
726      // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
727      @SuppressWarnings({"unchecked", "rawtypes"})
728      ImmutableList<Class<? super T>> collectedTypes =
729          (ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getRawTypes());
730      return FluentIterable.from(collectedTypes)
731          .filter(
732              new Predicate<Class<?>>() {
733                @Override
734                public boolean apply(Class<?> type) {
735                  return type.isInterface();
736                }
737              })
738          .toSet();
739    }
740
741    @Override
742    public TypeSet classes() {
743      throw new UnsupportedOperationException("interfaces().classes() not supported.");
744    }
745
746    private Object readResolve() {
747      return getTypes().interfaces();
748    }
749
750    private static final long serialVersionUID = 0;
751  }
752
753  private final class ClassSet extends TypeSet {
754
755    private transient @MonotonicNonNull ImmutableSet<TypeToken<? super T>> classes;
756
757    @Override
758    protected Set<TypeToken<? super T>> delegate() {
759      ImmutableSet<TypeToken<? super T>> result = classes;
760      if (result == null) {
761        @SuppressWarnings({"unchecked", "rawtypes"})
762        ImmutableList<TypeToken<? super T>> collectedTypes =
763            (ImmutableList)
764                TypeCollector.FOR_GENERIC_TYPE.classesOnly().collectTypes(TypeToken.this);
765        return (classes =
766            FluentIterable.from(collectedTypes)
767                .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
768                .toSet());
769      } else {
770        return result;
771      }
772    }
773
774    @Override
775    public TypeSet classes() {
776      return this;
777    }
778
779    @Override
780    public Set<Class<? super T>> rawTypes() {
781      // Java has no way to express ? super T when we parameterize TypeToken vs. Class.
782      @SuppressWarnings({"unchecked", "rawtypes"})
783      ImmutableList<Class<? super T>> collectedTypes =
784          (ImmutableList) TypeCollector.FOR_RAW_TYPE.classesOnly().collectTypes(getRawTypes());
785      return ImmutableSet.copyOf(collectedTypes);
786    }
787
788    @Override
789    public TypeSet interfaces() {
790      throw new UnsupportedOperationException("classes().interfaces() not supported.");
791    }
792
793    private Object readResolve() {
794      return getTypes().classes();
795    }
796
797    private static final long serialVersionUID = 0;
798  }
799
800  private enum TypeFilter implements Predicate<TypeToken<?>> {
801    IGNORE_TYPE_VARIABLE_OR_WILDCARD {
802      @Override
803      public boolean apply(TypeToken<?> type) {
804        return !(type.runtimeType instanceof TypeVariable
805            || type.runtimeType instanceof WildcardType);
806      }
807    },
808    INTERFACE_ONLY {
809      @Override
810      public boolean apply(TypeToken<?> type) {
811        return type.getRawType().isInterface();
812      }
813    }
814  }
815
816  /**
817   * Returns true if {@code o} is another {@code TypeToken} that represents the same {@link Type}.
818   */
819  @Override
820  public boolean equals(@Nullable Object o) {
821    if (o instanceof TypeToken) {
822      TypeToken<?> that = (TypeToken<?>) o;
823      return runtimeType.equals(that.runtimeType);
824    }
825    return false;
826  }
827
828  @Override
829  public int hashCode() {
830    return runtimeType.hashCode();
831  }
832
833  @Override
834  public String toString() {
835    return Types.toString(runtimeType);
836  }
837
838  /** Implemented to support serialization of subclasses. */
839  protected Object writeReplace() {
840    // TypeResolver just transforms the type to our own impls that are Serializable
841    // except TypeVariable.
842    return of(new TypeResolver().resolveType(runtimeType));
843  }
844
845  /**
846   * Ensures that this type token doesn't contain type variables, which can cause unchecked type
847   * errors for callers like {@link TypeToInstanceMap}.
848   */
849  @CanIgnoreReturnValue
850  final TypeToken<T> rejectTypeVariables() {
851    new TypeVisitor() {
852      @Override
853      void visitTypeVariable(TypeVariable<?> type) {
854        throw new IllegalArgumentException(
855            runtimeType + "contains a type variable and is not safe for the operation");
856      }
857
858      @Override
859      void visitWildcardType(WildcardType type) {
860        visit(type.getLowerBounds());
861        visit(type.getUpperBounds());
862      }
863
864      @Override
865      void visitParameterizedType(ParameterizedType type) {
866        visit(type.getActualTypeArguments());
867        visit(type.getOwnerType());
868      }
869
870      @Override
871      void visitGenericArrayType(GenericArrayType type) {
872        visit(type.getGenericComponentType());
873      }
874    }.visit(runtimeType);
875    return this;
876  }
877
878  private boolean someRawTypeIsSubclassOf(Class<?> superclass) {
879    for (Class<?> rawType : getRawTypes()) {
880      if (superclass.isAssignableFrom(rawType)) {
881        return true;
882      }
883    }
884    return false;
885  }
886
887  private boolean isSubtypeOfParameterizedType(ParameterizedType supertype) {
888    Class<?> matchedClass = of(supertype).getRawType();
889    if (!someRawTypeIsSubclassOf(matchedClass)) {
890      return false;
891    }
892    TypeVariable<?>[] typeVars = matchedClass.getTypeParameters();
893    Type[] supertypeArgs = supertype.getActualTypeArguments();
894    for (int i = 0; i < typeVars.length; i++) {
895      Type subtypeParam = getCovariantTypeResolver().resolveType(typeVars[i]);
896      // If 'supertype' is "List<? extends CharSequence>"
897      // and 'this' is StringArrayList,
898      // First step is to figure out StringArrayList "is-a" List<E> where <E> = String.
899      // String is then matched against <? extends CharSequence>, the supertypeArgs[0].
900      if (!of(subtypeParam).is(supertypeArgs[i], typeVars[i])) {
901        return false;
902      }
903    }
904    // We only care about the case when the supertype is a non-static inner class
905    // in which case we need to make sure the subclass's owner type is a subtype of the
906    // supertype's owner.
907    return Modifier.isStatic(((Class<?>) supertype.getRawType()).getModifiers())
908        || supertype.getOwnerType() == null
909        || isOwnedBySubtypeOf(supertype.getOwnerType());
910  }
911
912  private boolean isSubtypeOfArrayType(GenericArrayType supertype) {
913    if (runtimeType instanceof Class) {
914      Class<?> fromClass = (Class<?>) runtimeType;
915      if (!fromClass.isArray()) {
916        return false;
917      }
918      return of(fromClass.getComponentType()).isSubtypeOf(supertype.getGenericComponentType());
919    } else if (runtimeType instanceof GenericArrayType) {
920      GenericArrayType fromArrayType = (GenericArrayType) runtimeType;
921      return of(fromArrayType.getGenericComponentType())
922          .isSubtypeOf(supertype.getGenericComponentType());
923    } else {
924      return false;
925    }
926  }
927
928  private boolean isSupertypeOfArray(GenericArrayType subtype) {
929    if (runtimeType instanceof Class) {
930      Class<?> thisClass = (Class<?>) runtimeType;
931      if (!thisClass.isArray()) {
932        return thisClass.isAssignableFrom(Object[].class);
933      }
934      return of(subtype.getGenericComponentType()).isSubtypeOf(thisClass.getComponentType());
935    } else if (runtimeType instanceof GenericArrayType) {
936      return of(subtype.getGenericComponentType())
937          .isSubtypeOf(((GenericArrayType) runtimeType).getGenericComponentType());
938    } else {
939      return false;
940    }
941  }
942
943  /**
944   * {@code A.is(B)} is defined as {@code Foo<A>.isSubtypeOf(Foo<B>)}.
945   *
946   * <p>Specifically, returns true if any of the following conditions is met:
947   * <ol>
948   *   <li>'this' and {@code formalType} are equal.
949   *   <li>'this' and {@code formalType} have equal canonical form.
950   *   <li>{@code formalType} is {@code <? extends Foo>} and 'this' is a subtype of {@code Foo}.
951   *   <li>{@code formalType} is {@code <? super Foo>} and 'this' is a supertype of {@code Foo}.
952   * </ol>
953   * Note that condition 2 isn't technically accurate under the context of a recursively
954   * bounded type variables. For example, {@code Enum<? extends Enum<E>>} canonicalizes to
955   * {@code Enum<?>} where {@code E} is the type variable declared on the {@code Enum} class
956   * declaration. It's technically <em>not</em> true that {@code Foo<Enum<? extends Enum<E>>>} is a
957   * subtype of {@code Foo<Enum<?>>} according to JLS. See testRecursiveWildcardSubtypeBug() for
958   * a real example.
959   *
960   * <p>It appears that properly handling recursive type bounds in the presence of implicit type
961   * bounds is not easy. For now we punt, hoping that this defect should rarely cause issues in real
962   * code.
963   *
964   * @param formalType is {@code Foo<formalType>} a supertype of {@code Foo<T>}?
965   * @param declaration The type variable in the context of a parameterized type. Used to infer
966   *        type bound when {@code formalType} is a wildcard with implicit upper bound.
967   */
968  private boolean is(Type formalType, TypeVariable<?> declaration) {
969    if (runtimeType.equals(formalType)) {
970      return true;
971    }
972    if (formalType instanceof WildcardType) {
973      WildcardType your = canonicalizeWildcardType(declaration, (WildcardType) formalType);
974      // if "formalType" is <? extends Foo>, "this" can be:
975      // Foo, SubFoo, <? extends Foo>, <? extends SubFoo>, <T extends Foo> or
976      // <T extends SubFoo>.
977      // if "formalType" is <? super Foo>, "this" can be:
978      // Foo, SuperFoo, <? super Foo> or <? super SuperFoo>.
979      return every(your.getUpperBounds()).isSupertypeOf(runtimeType)
980          && every(your.getLowerBounds()).isSubtypeOf(runtimeType);
981    }
982    return canonicalizeWildcardsInType(runtimeType)
983        .equals(canonicalizeWildcardsInType(formalType));
984  }
985
986  /**
987   * In reflection, {@code Foo<?>.getUpperBounds()[0]} is always {@code Object.class}, even when Foo
988   * is defined as {@code Foo<T extends String>}. Thus directly calling {@code <?>.is(String.class)}
989   * will return false. To mitigate, we canonicalize wildcards by enforcing the following
990   * invariants:
991   * <ol>
992   * <li>{@code canonicalize(t)} always produces the equal result for equivalent types. For example
993   *     both {@code Enum<?>} and {@code Enum<? extends Enum<?>>} canonicalize to
994   *     {@code Enum<? extends Enum<E>}.
995   * <li>{@code canonicalize(t)} produces a "literal" supertype of t.
996   *     For example: {@code Enum<? extends Enum<?>>} canonicalizes to {@code Enum<?>}, which is
997   *     a supertype (if we disregard the upper bound is implicitly an Enum too).
998   * <li>If {@code canonicalize(A) == canonicalize(B)}, then {@code Foo<A>.isSubtypeOf(Foo<B>)} and
999   *     vice versa. i.e. {@code A.is(B)} and {@code B.is(A)}.
1000   * <li>{@code canonicalize(canonicalize(A)) == canonicalize(A)}.
1001   * </ol>
1002   */
1003  private static Type canonicalizeTypeArg(TypeVariable<?> declaration, Type typeArg) {
1004    return typeArg instanceof WildcardType
1005        ? canonicalizeWildcardType(declaration, ((WildcardType) typeArg))
1006        : canonicalizeWildcardsInType(typeArg);
1007  }
1008
1009  private static Type canonicalizeWildcardsInType(Type type) {
1010    if (type instanceof ParameterizedType) {
1011      return canonicalizeWildcardsInParameterizedType((ParameterizedType) type);
1012    }
1013    if (type instanceof GenericArrayType) {
1014      return Types.newArrayType(
1015          canonicalizeWildcardsInType(((GenericArrayType) type).getGenericComponentType()));
1016    }
1017    return type;
1018  }
1019
1020  // WARNING: the returned type may have empty upper bounds, which may violate common expectations
1021  // by user code or even some of our own code. It's fine for the purpose of checking subtypes.
1022  // Just don't ever let the user access it.
1023  private static WildcardType canonicalizeWildcardType(
1024      TypeVariable<?> declaration, WildcardType type) {
1025    Type[] declared = declaration.getBounds();
1026    List<Type> upperBounds = new ArrayList<>();
1027    for (Type bound : type.getUpperBounds()) {
1028      if (!any(declared).isSubtypeOf(bound)) {
1029        upperBounds.add(canonicalizeWildcardsInType(bound));
1030      }
1031    }
1032    return new Types.WildcardTypeImpl(type.getLowerBounds(), upperBounds.toArray(new Type[0]));
1033  }
1034
1035  private static ParameterizedType canonicalizeWildcardsInParameterizedType(
1036      ParameterizedType type) {
1037    Class<?> rawType = (Class<?>) type.getRawType();
1038    TypeVariable<?>[] typeVars = rawType.getTypeParameters();
1039    Type[] typeArgs = type.getActualTypeArguments();
1040    for (int i = 0; i < typeArgs.length; i++) {
1041      typeArgs[i] = canonicalizeTypeArg(typeVars[i], typeArgs[i]);
1042    }
1043    return Types.newParameterizedTypeWithOwner(type.getOwnerType(), rawType, typeArgs);
1044  }
1045
1046  private static Bounds every(Type[] bounds) {
1047    // Every bound must match. On any false, result is false.
1048    return new Bounds(bounds, false);
1049  }
1050
1051  private static Bounds any(Type[] bounds) {
1052    // Any bound matches. On any true, result is true.
1053    return new Bounds(bounds, true);
1054  }
1055
1056  private static class Bounds {
1057    private final Type[] bounds;
1058    private final boolean target;
1059
1060    Bounds(Type[] bounds, boolean target) {
1061      this.bounds = bounds;
1062      this.target = target;
1063    }
1064
1065    boolean isSubtypeOf(Type supertype) {
1066      for (Type bound : bounds) {
1067        if (of(bound).isSubtypeOf(supertype) == target) {
1068          return target;
1069        }
1070      }
1071      return !target;
1072    }
1073
1074    boolean isSupertypeOf(Type subtype) {
1075      TypeToken<?> type = of(subtype);
1076      for (Type bound : bounds) {
1077        if (type.isSubtypeOf(bound) == target) {
1078          return target;
1079        }
1080      }
1081      return !target;
1082    }
1083  }
1084
1085  private ImmutableSet<Class<? super T>> getRawTypes() {
1086    final ImmutableSet.Builder<Class<?>> builder = ImmutableSet.builder();
1087    new TypeVisitor() {
1088      @Override
1089      void visitTypeVariable(TypeVariable<?> t) {
1090        visit(t.getBounds());
1091      }
1092
1093      @Override
1094      void visitWildcardType(WildcardType t) {
1095        visit(t.getUpperBounds());
1096      }
1097
1098      @Override
1099      void visitParameterizedType(ParameterizedType t) {
1100        builder.add((Class<?>) t.getRawType());
1101      }
1102
1103      @Override
1104      void visitClass(Class<?> t) {
1105        builder.add(t);
1106      }
1107
1108      @Override
1109      void visitGenericArrayType(GenericArrayType t) {
1110        builder.add(Types.getArrayClass(of(t.getGenericComponentType()).getRawType()));
1111      }
1112    }.visit(runtimeType);
1113    // Cast from ImmutableSet<Class<?>> to ImmutableSet<Class<? super T>>
1114    @SuppressWarnings({"unchecked", "rawtypes"})
1115    ImmutableSet<Class<? super T>> result = (ImmutableSet) builder.build();
1116    return result;
1117  }
1118
1119  private boolean isOwnedBySubtypeOf(Type supertype) {
1120    for (TypeToken<?> type : getTypes()) {
1121      Type ownerType = type.getOwnerTypeIfPresent();
1122      if (ownerType != null && of(ownerType).isSubtypeOf(supertype)) {
1123        return true;
1124      }
1125    }
1126    return false;
1127  }
1128
1129  /**
1130   * Returns the owner type of a {@link ParameterizedType} or enclosing class of a {@link Class}, or
1131   * null otherwise.
1132   */
1133  private @Nullable Type getOwnerTypeIfPresent() {
1134    if (runtimeType instanceof ParameterizedType) {
1135      return ((ParameterizedType) runtimeType).getOwnerType();
1136    } else if (runtimeType instanceof Class<?>) {
1137      return ((Class<?>) runtimeType).getEnclosingClass();
1138    } else {
1139      return null;
1140    }
1141  }
1142
1143  /**
1144   * Returns the type token representing the generic type declaration of {@code cls}. For example:
1145   * {@code TypeToken.getGenericType(Iterable.class)} returns {@code Iterable<T>}.
1146   *
1147   * <p>If {@code cls} isn't parameterized and isn't a generic array, the type token of the class is
1148   * returned.
1149   */
1150  @VisibleForTesting
1151  static <T> TypeToken<? extends T> toGenericType(Class<T> cls) {
1152    if (cls.isArray()) {
1153      Type arrayOfGenericType =
1154          Types.newArrayType(
1155              // If we are passed with int[].class, don't turn it to GenericArrayType
1156              toGenericType(cls.getComponentType()).runtimeType);
1157      @SuppressWarnings("unchecked") // array is covariant
1158      TypeToken<? extends T> result = (TypeToken<? extends T>) of(arrayOfGenericType);
1159      return result;
1160    }
1161    TypeVariable<Class<T>>[] typeParams = cls.getTypeParameters();
1162    Type ownerType =
1163        cls.isMemberClass() && !Modifier.isStatic(cls.getModifiers())
1164            ? toGenericType(cls.getEnclosingClass()).runtimeType
1165            : null;
1166
1167    if ((typeParams.length > 0) || ((ownerType != null) && ownerType != cls.getEnclosingClass())) {
1168      @SuppressWarnings("unchecked") // Like, it's Iterable<T> for Iterable.class
1169      TypeToken<? extends T> type =
1170          (TypeToken<? extends T>)
1171              of(Types.newParameterizedTypeWithOwner(ownerType, cls, typeParams));
1172      return type;
1173    } else {
1174      return of(cls);
1175    }
1176  }
1177
1178  private TypeResolver getCovariantTypeResolver() {
1179    TypeResolver resolver = covariantTypeResolver;
1180    if (resolver == null) {
1181      resolver = (covariantTypeResolver = TypeResolver.covariantly(runtimeType));
1182    }
1183    return resolver;
1184  }
1185
1186  private TypeResolver getInvariantTypeResolver() {
1187    TypeResolver resolver = invariantTypeResolver;
1188    if (resolver == null) {
1189      resolver = (invariantTypeResolver = TypeResolver.invariantly(runtimeType));
1190    }
1191    return resolver;
1192  }
1193
1194  private TypeToken<? super T> getSupertypeFromUpperBounds(
1195      Class<? super T> supertype, Type[] upperBounds) {
1196    for (Type upperBound : upperBounds) {
1197      @SuppressWarnings("unchecked") // T's upperbound is <? super T>.
1198      TypeToken<? super T> bound = (TypeToken<? super T>) of(upperBound);
1199      if (bound.isSubtypeOf(supertype)) {
1200        @SuppressWarnings({"rawtypes", "unchecked"}) // guarded by the isSubtypeOf check.
1201        TypeToken<? super T> result = bound.getSupertype((Class) supertype);
1202        return result;
1203      }
1204    }
1205    throw new IllegalArgumentException(supertype + " isn't a super type of " + this);
1206  }
1207
1208  private TypeToken<? extends T> getSubtypeFromLowerBounds(Class<?> subclass, Type[] lowerBounds) {
1209    for (Type lowerBound : lowerBounds) {
1210      @SuppressWarnings("unchecked") // T's lower bound is <? extends T>
1211      TypeToken<? extends T> bound = (TypeToken<? extends T>) of(lowerBound);
1212      // Java supports only one lowerbound anyway.
1213      return bound.getSubtype(subclass);
1214    }
1215    throw new IllegalArgumentException(subclass + " isn't a subclass of " + this);
1216  }
1217
1218  private TypeToken<? super T> getArraySupertype(Class<? super T> supertype) {
1219    // with component type, we have lost generic type information
1220    // Use raw type so that compiler allows us to call getSupertype()
1221    @SuppressWarnings("rawtypes")
1222    TypeToken componentType =
1223        checkNotNull(getComponentType(), "%s isn't a super type of %s", supertype, this);
1224    // array is covariant. component type is super type, so is the array type.
1225    @SuppressWarnings("unchecked") // going from raw type back to generics
1226    TypeToken<?> componentSupertype = componentType.getSupertype(supertype.getComponentType());
1227    @SuppressWarnings("unchecked") // component type is super type, so is array type.
1228    TypeToken<? super T> result =
1229        (TypeToken<? super T>)
1230            // If we are passed with int[].class, don't turn it to GenericArrayType
1231            of(newArrayClassOrGenericArrayType(componentSupertype.runtimeType));
1232    return result;
1233  }
1234
1235  private TypeToken<? extends T> getArraySubtype(Class<?> subclass) {
1236    // array is covariant. component type is subtype, so is the array type.
1237    TypeToken<?> componentSubtype = getComponentType().getSubtype(subclass.getComponentType());
1238    @SuppressWarnings("unchecked") // component type is subtype, so is array type.
1239    TypeToken<? extends T> result =
1240        (TypeToken<? extends T>)
1241            // If we are passed with int[].class, don't turn it to GenericArrayType
1242            of(newArrayClassOrGenericArrayType(componentSubtype.runtimeType));
1243    return result;
1244  }
1245
1246  private Type resolveTypeArgsForSubclass(Class<?> subclass) {
1247    // If both runtimeType and subclass are not parameterized, return subclass
1248    // If runtimeType is not parameterized but subclass is, process subclass as a parameterized type
1249    // If runtimeType is a raw type (i.e. is a parameterized type specified as a Class<?>), we
1250    // return subclass as a raw type
1251    if (runtimeType instanceof Class
1252        && ((subclass.getTypeParameters().length == 0)
1253            || (getRawType().getTypeParameters().length != 0))) {
1254      // no resolution needed
1255      return subclass;
1256    }
1257    // class Base<A, B> {}
1258    // class Sub<X, Y> extends Base<X, Y> {}
1259    // Base<String, Integer>.subtype(Sub.class):
1260
1261    // Sub<X, Y>.getSupertype(Base.class) => Base<X, Y>
1262    // => X=String, Y=Integer
1263    // => Sub<X, Y>=Sub<String, Integer>
1264    TypeToken<?> genericSubtype = toGenericType(subclass);
1265    @SuppressWarnings({"rawtypes", "unchecked"}) // subclass isn't <? extends T>
1266    Type supertypeWithArgsFromSubtype =
1267        genericSubtype.getSupertype((Class) getRawType()).runtimeType;
1268    return new TypeResolver()
1269        .where(supertypeWithArgsFromSubtype, runtimeType)
1270        .resolveType(genericSubtype.runtimeType);
1271  }
1272
1273  /**
1274   * Creates an array class if {@code componentType} is a class, or else, a {@link
1275   * GenericArrayType}. This is what Java7 does for generic array type parameters.
1276   */
1277  private static Type newArrayClassOrGenericArrayType(Type componentType) {
1278    return Types.JavaVersion.JAVA7.newArrayType(componentType);
1279  }
1280
1281  private static final class SimpleTypeToken<T> extends TypeToken<T> {
1282
1283    SimpleTypeToken(Type type) {
1284      super(type);
1285    }
1286
1287    private static final long serialVersionUID = 0;
1288  }
1289
1290  /**
1291   * Collects parent types from a sub type.
1292   *
1293   * @param <K> The type "kind". Either a TypeToken, or Class.
1294   */
1295  private abstract static class TypeCollector<K> {
1296
1297    static final TypeCollector<TypeToken<?>> FOR_GENERIC_TYPE =
1298        new TypeCollector<TypeToken<?>>() {
1299          @Override
1300          Class<?> getRawType(TypeToken<?> type) {
1301            return type.getRawType();
1302          }
1303
1304          @Override
1305          Iterable<? extends TypeToken<?>> getInterfaces(TypeToken<?> type) {
1306            return type.getGenericInterfaces();
1307          }
1308
1309          @Override
1310          @Nullable
1311          TypeToken<?> getSuperclass(TypeToken<?> type) {
1312            return type.getGenericSuperclass();
1313          }
1314        };
1315
1316    static final TypeCollector<Class<?>> FOR_RAW_TYPE =
1317        new TypeCollector<Class<?>>() {
1318          @Override
1319          Class<?> getRawType(Class<?> type) {
1320            return type;
1321          }
1322
1323          @Override
1324          Iterable<? extends Class<?>> getInterfaces(Class<?> type) {
1325            return Arrays.asList(type.getInterfaces());
1326          }
1327
1328          @Override
1329          @Nullable
1330          Class<?> getSuperclass(Class<?> type) {
1331            return type.getSuperclass();
1332          }
1333        };
1334
1335    /** For just classes, we don't have to traverse interfaces. */
1336    final TypeCollector<K> classesOnly() {
1337      return new ForwardingTypeCollector<K>(this) {
1338        @Override
1339        Iterable<? extends K> getInterfaces(K type) {
1340          return ImmutableSet.of();
1341        }
1342
1343        @Override
1344        ImmutableList<K> collectTypes(Iterable<? extends K> types) {
1345          ImmutableList.Builder<K> builder = ImmutableList.builder();
1346          for (K type : types) {
1347            if (!getRawType(type).isInterface()) {
1348              builder.add(type);
1349            }
1350          }
1351          return super.collectTypes(builder.build());
1352        }
1353      };
1354    }
1355
1356    final ImmutableList<K> collectTypes(K type) {
1357      return collectTypes(ImmutableList.of(type));
1358    }
1359
1360    ImmutableList<K> collectTypes(Iterable<? extends K> types) {
1361      // type -> order number. 1 for Object, 2 for anything directly below, so on so forth.
1362      Map<K, Integer> map = Maps.newHashMap();
1363      for (K type : types) {
1364        collectTypes(type, map);
1365      }
1366      return sortKeysByValue(map, Ordering.natural().reverse());
1367    }
1368
1369    /** Collects all types to map, and returns the total depth from T up to Object. */
1370    @CanIgnoreReturnValue
1371    private int collectTypes(K type, Map<? super K, Integer> map) {
1372      Integer existing = map.get(type);
1373      if (existing != null) {
1374        // short circuit: if set contains type it already contains its supertypes
1375        return existing;
1376      }
1377      // Interfaces should be listed before Object.
1378      int aboveMe = getRawType(type).isInterface() ? 1 : 0;
1379      for (K interfaceType : getInterfaces(type)) {
1380        aboveMe = Math.max(aboveMe, collectTypes(interfaceType, map));
1381      }
1382      K superclass = getSuperclass(type);
1383      if (superclass != null) {
1384        aboveMe = Math.max(aboveMe, collectTypes(superclass, map));
1385      }
1386      /*
1387       * TODO(benyu): should we include Object for interface? Also, CharSequence[] and Object[] for
1388       * String[]?
1389       *
1390       */
1391      map.put(type, aboveMe + 1);
1392      return aboveMe + 1;
1393    }
1394
1395    private static <K, V> ImmutableList<K> sortKeysByValue(
1396        final Map<K, V> map, final Comparator<? super V> valueComparator) {
1397      Ordering<K> keyOrdering =
1398          new Ordering<K>() {
1399            @Override
1400            public int compare(K left, K right) {
1401              return valueComparator.compare(map.get(left), map.get(right));
1402            }
1403          };
1404      return keyOrdering.immutableSortedCopy(map.keySet());
1405    }
1406
1407    abstract Class<?> getRawType(K type);
1408
1409    abstract Iterable<? extends K> getInterfaces(K type);
1410
1411    abstract @Nullable K getSuperclass(K type);
1412
1413    private static class ForwardingTypeCollector<K> extends TypeCollector<K> {
1414
1415      private final TypeCollector<K> delegate;
1416
1417      ForwardingTypeCollector(TypeCollector<K> delegate) {
1418        this.delegate = delegate;
1419      }
1420
1421      @Override
1422      Class<?> getRawType(K type) {
1423        return delegate.getRawType(type);
1424      }
1425
1426      @Override
1427      Iterable<? extends K> getInterfaces(K type) {
1428        return delegate.getInterfaces(type);
1429      }
1430
1431      @Override
1432      K getSuperclass(K type) {
1433        return delegate.getSuperclass(type);
1434      }
1435    }
1436  }
1437
1438  // This happens to be the hash of the class as of now. So setting it makes a backward compatible
1439  // change. Going forward, if any incompatible change is added, we can change the UID back to 1.
1440  private static final long serialVersionUID = 3637540370352322684L;
1441}