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