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