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