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