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