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    
017    package com.google.common.reflect;
018    
019    import static com.google.common.base.Preconditions.checkArgument;
020    import static com.google.common.base.Preconditions.checkNotNull;
021    import static com.google.common.base.Preconditions.checkState;
022    
023    import com.google.common.annotations.Beta;
024    import com.google.common.annotations.VisibleForTesting;
025    import com.google.common.base.Predicate;
026    import com.google.common.collect.AbstractSequentialIterator;
027    import com.google.common.collect.ForwardingSet;
028    import com.google.common.collect.ImmutableList;
029    import com.google.common.collect.ImmutableMap;
030    import com.google.common.collect.ImmutableSet;
031    import com.google.common.collect.ImmutableSortedSet;
032    import com.google.common.collect.Iterables;
033    import com.google.common.collect.Iterators;
034    import com.google.common.collect.Maps;
035    import com.google.common.collect.Ordering;
036    import com.google.common.collect.Sets;
037    
038    import java.io.Serializable;
039    import java.lang.reflect.GenericArrayType;
040    import java.lang.reflect.ParameterizedType;
041    import java.lang.reflect.Type;
042    import java.lang.reflect.TypeVariable;
043    import java.lang.reflect.WildcardType;
044    import java.util.Comparator;
045    import java.util.Map;
046    import java.util.Set;
047    import java.util.SortedSet;
048    
049    import 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 instance {@link #isAssignableFrom}, {@link #isArray} and {@link
056     * #getGenericInterfaces} 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     *
063     *   new TypeToken<List<String>>() {}
064     * }</pre>
065     * Note that it's critical that the actual type argument is carried by a subclass.
066     * The following code is wrong because it only captures the {@code <T>} type variable
067     * of the {@code listType()} method signature; while {@code <String>} is lost in erasure:
068     * <pre>   {@code
069     *
070     *   class Util {
071     *     static <T> TypeToken<List<T>> listType() {
072     *       return new TypeToken<List<T>>() {};
073     *     }
074     *   }
075     *
076     *   TypeToken<List<String>> stringListType = Util.<String>listType();
077     * }</pre>
078     * <li>Capture a generic type with a (usually anonymous) subclass and resolve it against
079     * a context class that knows what the type parameters are. For example: <pre>   {@code
080     *   abstract class IKnowMyType<T> {
081     *     TypeToken<T> type = new TypeToken<T>(getClass()) {};
082     *   }
083     *   new IKnowMyType<String>() {}.type => String
084     * }</pre>
085     * </ul>
086     *
087     * <p>{@code TypeToken} is serializable when no type variable is contained in the type.
088     *
089     * <p>Note to Guice users: {@code} TypeToken is similar to Guice's {@code TypeLiteral} class,
090     * but with one important difference: it supports non-reified types such as {@code T},
091     * {@code List<T>} or even {@code List<? extends Number>}; while TypeLiteral does not.
092     * TypeToken is also serializable and offers numerous additional utility methods.
093     *
094     * @author Bob Lee
095     * @author Sven Mawson
096     * @author Ben Yu
097     * @since 12.0
098     */
099    @Beta
100    @SuppressWarnings("serial") // SimpleTypeToken is the serialized form.
101    public abstract class TypeToken<T> extends TypeCapture<T> implements Serializable {
102    
103      private final Type runtimeType;
104    
105      /** Resolver for resolving types with {@link #runtimeType} as context. */
106      private transient TypeResolver typeResolver;
107    
108      /**
109       * Constructs a new type token of {@code T}.
110       *
111       * <p>Clients create an empty anonymous subclass. Doing so embeds the type
112       * parameter in the anonymous class's type hierarchy so we can reconstitute
113       * it at runtime despite erasure.
114       *
115       * <p>For example: <pre>   {@code
116       *
117       *   TypeToken<List<String>> t = new TypeToken<List<String>>() {};
118       * }</pre>
119       */
120      protected TypeToken() {
121        this.runtimeType = capture();
122        checkState(!(runtimeType instanceof TypeVariable<?>),
123            "Cannot construct a TypeToken for a type variable.\n" +
124            "You probably meant to call new TypeToken<%s>(getClass()) " +
125            "that can resolve the type variable for you.\n" +
126            "If you do need to create a TypeToken of a type variable, " +
127            "please use TypeToken.of() instead.", runtimeType);
128      }
129    
130      /**
131       * Constructs a new type token of {@code T}. Free type variables are resolved against {@code
132       * declaringClass}.
133       *
134       * <p>Clients create an empty anonymous subclass. Doing so embeds the type
135       * parameter in the anonymous class's type hierarchy so we can reconstitute
136       * it at runtime despite erasure.
137       *
138       * <p>For example: <pre>   {@code
139       *
140       *   abstract class IKnowMyType<T> {
141       *     TypeToken<T> getMyType() {
142       *       return new TypeToken<T>(getClass()) {};
143       *     }
144       *   }
145       *
146       *   new IKnowMyType<String>() {}.getMyType() => String
147       * }</pre>
148       */
149      protected TypeToken(Class<?> declaringClass) {
150        Type captured = super.capture();
151        if (captured instanceof Class) {
152          this.runtimeType = captured;
153        } else {
154          this.runtimeType = of(declaringClass).resolveType(captured).runtimeType;
155        }
156      }
157    
158      private TypeToken(Type type) {
159        this.runtimeType = checkNotNull(type);
160      }
161    
162      /** Returns an instance of type token that wraps {@code type}. */
163      public static <T> TypeToken<T> of(Class<T> type) {
164        return new SimpleTypeToken<T>(type);
165      }
166    
167      /** Returns an instance of type token that wraps {@code type}. */
168      public static TypeToken<?> of(Type type) {
169        return new SimpleTypeToken<Object>(type);
170      }
171    
172      /**
173       * Returns the raw type of {@code T}. Formally speaking, if {@code T} is returned by
174       * {@link java.lang.reflect.Method#getGenericReturnType}, the raw type is what's returned by
175       * {@link java.lang.reflect.Method#getReturnType} of the same method object. Specifically:
176       * <ul>
177       * <li>If {@code T} is a {@code Class} itself, {@code T} itself is returned.
178       * <li>If {@code T} is a {@link ParameterizedType}, the raw type of the parameterized type is
179       *     returned.
180       * <li>If {@code T} is a {@link GenericArrayType}, the returned type is the corresponding array
181       *     class. For example: {@code List<Integer>[] => List[]}.
182       * <li>If {@code T} is a type variable or a wildcard type, the raw type of the first upper bound
183       *     is returned. For example: {@code <X extends Foo> => Foo}.
184       * </ul>
185       */
186      public final Class<? super T> getRawType() {
187        Class<?> rawType = getRawType(runtimeType);
188        @SuppressWarnings("unchecked") // raw type is |T|
189        Class<? super T> result = (Class<? super T>) rawType;
190        return result;
191      }
192    
193      /** Returns the resolved type of the represented type token. */
194      public final Type getType() {
195        return runtimeType;
196      }
197    
198      /**
199       * Returns a new {@code TypeToken} where type variables represented by {@code typeParam}
200       * are substituted by the {@code typeArg}. For example, it can be used to construct
201       * {@code Map<K, V>} for any {@code K} and {@code V} type: <pre>   {@code
202       *
203       *   static <K, V> TypeToken<Map<K, V>> mapOf(
204       *       TypeToken<K> keyType, TypeToken<V> valueType) {
205       *     return new TypeToken<Map<K, V>>() {}
206       *         .where(new TypeParameter<K>() {}, keyType)
207       *         .where(new TypeParameter<V>() {}, valueType);
208       *   }
209       * }</pre>
210       *
211       * @param <X> The parameter type
212       * @param typeParam the parameter type variable
213       * @param typeArg the actual type to substitute
214       */
215      public final <X> TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg) {
216        TypeResolver resolver = new TypeResolver()
217            .where(ImmutableMap.of(typeParam.typeVariable, typeArg.runtimeType));
218        // If there's any type error, we'd report now rather than later.
219        return new SimpleTypeToken<T>(resolver.resolve(runtimeType));
220      }
221    
222      /**
223       * Returns a new {@code TypeToken} where type variables represented by {@code typeParam}
224       * are substituted by the {@code typeArg}. For example, it can be used to construct
225       * {@code Map<K, V>} for any {@code K} and {@code V} type: <pre>   {@code
226       *
227       *   static <K, V> TypeToken<Map<K, V>> mapOf(
228       *       Class<K> keyType, Class<V> valueType) {
229       *     return new TypeToken<Map<K, V>>() {}
230       *         .where(new TypeParameter<K>() {}, keyType)
231       *         .where(new TypeParameter<V>() {}, valueType);
232       *   }
233       * }</pre>
234       *
235       * @param <X> The parameter type
236       * @param typeParam the parameter type variable
237       * @param typeArg the actual type to substitute
238       */
239      public final <X> TypeToken<T> where(TypeParameter<X> typeParam, Class<X> typeArg) {
240        return where(typeParam, of(typeArg));
241      }
242    
243      /**
244       * Resolves the given {@code type} against the type context represented by this type.
245       * For example: <pre>   {@code
246       *
247       *   new TypeToken<List<String>>() {}.resolveType(
248       *       List.class.getMethod("get", int.class).getGenericReturnType())
249       *   => String.class
250       * }</pre>
251       */
252      public final TypeToken<?> resolveType(Type type) {
253        checkNotNull(type);
254        TypeResolver resolver = typeResolver;
255        if (resolver == null) {
256          resolver = (typeResolver = TypeResolver.accordingTo(runtimeType));
257        }
258        return of(resolver.resolve(type));
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 {@link
271       * Class#getGenericSuperclass}. For example, {@code
272       * new TypeToken<StringArrayList>() {}.getGenericSuperclass()} will return {@code
273       * new TypeToken<ArrayList<String>>() {}}; while {@code
274       * StringArrayList.class.getGenericSuperclass()} will return {@code ArrayList<E>}, where {@code E}
275       * is the type variable declared by class {@code ArrayList}.
276       *
277       * <p>If this type is a type variable or wildcard, its first upper bound is examined and returned
278       * if the bound is a class or extends from a class. This means that the returned type could be a
279       * type variable too.
280       */
281      @Nullable
282      final TypeToken<? super T> getGenericSuperclass() {
283        if (runtimeType instanceof TypeVariable) {
284          // First bound is always the super class, if one exists.
285          return boundAsSuperclass(((TypeVariable<?>) runtimeType).getBounds()[0]);
286        }
287        if (runtimeType instanceof WildcardType) {
288          // wildcard has one and only one upper bound.
289          return boundAsSuperclass(((WildcardType) runtimeType).getUpperBounds()[0]);
290        }
291        Type superclass = getRawType().getGenericSuperclass();
292        if (superclass == null) {
293          return null;
294        }
295        @SuppressWarnings("unchecked") // super class of T
296        TypeToken<? super T> superToken = (TypeToken<? super T>) resolveSupertype(superclass);
297        return superToken;
298      }
299    
300      @Nullable 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
313       * new 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 = (TypeToken<? super T>)
333              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
369       * input {@code Iterable.class}.
370       */
371      public final TypeToken<? super T> getSupertype(Class<? super T> superclass) {
372        checkArgument(superclass.isAssignableFrom(getRawType()),
373            "%s is not a super class of %s", superclass, this);
374        if (runtimeType instanceof TypeVariable) {
375          return getSupertypeFromUpperBounds(superclass, ((TypeVariable<?>) runtimeType).getBounds());
376        }
377        if (runtimeType instanceof WildcardType) {
378          return getSupertypeFromUpperBounds(superclass, ((WildcardType) runtimeType).getUpperBounds());
379        }
380        if (superclass.isArray()) {
381          return getArraySupertype(superclass);
382        }
383        @SuppressWarnings("unchecked") // resolved supertype
384        TypeToken<? super T> supertype = (TypeToken<? super T>)
385            resolveSupertype(toGenericType(superclass).runtimeType);
386        return supertype;
387      }
388    
389      /**
390       * Returns subtype of {@code this} with {@code subclass} as the raw class.
391       * For example, if this is {@code Iterable<String>} and {@code subclass} is {@code List},
392       * {@code List<String>} is returned.
393       */
394      public final TypeToken<? extends T> getSubtype(Class<?> subclass) {
395        checkArgument(!(runtimeType instanceof TypeVariable),
396            "Cannot get subtype of type variable <%s>", this);
397        if (runtimeType instanceof WildcardType) {
398          return getSubtypeFromLowerBounds(subclass, ((WildcardType) runtimeType).getLowerBounds());
399        }
400        checkArgument(getRawType().isAssignableFrom(subclass),
401            "%s isn't a subclass of %s", subclass, this);
402        // unwrap array type if necessary
403        if (isArray()) {
404          return getArraySubtype(subclass);
405        }
406        @SuppressWarnings("unchecked") // guarded by the isAssignableFrom() statement above
407        TypeToken<? extends T> subtype = (TypeToken<? extends T>)
408            of(resolveTypeArgsForSubclass(subclass));
409        return subtype;
410      }
411    
412      /** Returns true if this type is assignable from the given {@code type}. */
413      public final boolean isAssignableFrom(TypeToken<?> type) {
414        return isAssignableFrom(type.runtimeType);
415      }
416    
417      /** Check if this type is assignable from the given {@code type}. */
418      public final boolean isAssignableFrom(Type type) {
419        return isAssignable(checkNotNull(type), runtimeType);
420      }
421    
422      /** Returns true if this type is known to be an array type. */
423      public final boolean isArray() {
424        return getComponentType() != null;
425      }
426    
427      /**
428       * Returns the Type representing the component type of an array. If this type does not represent
429       * an array type this method returns null.
430       */
431      @Nullable public final TypeToken<?> getComponentType() {
432        Type componentType = Types.getComponentType(runtimeType);
433        if (componentType == null) {
434          return null;
435        }
436        return of(componentType);
437      }
438    
439      /**
440       * The set of interfaces and classes that {@code T} is or is a subtype of. {@link Object} is not
441       * included in the set if this type is an interface.
442       */
443      public class TypeSet extends ForwardingSet<TypeToken<? super T>> implements Serializable {
444    
445        private transient ImmutableSet<TypeToken<? super T>> types;
446    
447        TypeSet() {}
448    
449        /** Returns the types that are interfaces implemented by this type. */
450        public TypeSet interfaces() {
451          return new InterfaceSet(this);
452        }
453    
454        /** Returns the types that are classes. */
455        public TypeSet classes() {
456          return new ClassSet();
457        }
458    
459        @Override protected Set<TypeToken<? super T>> delegate() {
460          ImmutableSet<TypeToken<? super T>> filteredTypes = types;
461          if (filteredTypes == null) {
462            return (types = ImmutableSet.copyOf(
463                Sets.filter(findAllTypes(), TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)));
464          } else {
465            return filteredTypes;
466          }
467        }
468    
469        /** Returns the raw types of the types in this set, in the same order. */
470        public final Set<Class<? super T>> rawTypes() {
471          ImmutableSet.Builder<Class<? super T>> builder = ImmutableSet.builder();
472          for (TypeToken<? super T> type : this) {
473            builder.add(type.getRawType());
474          }
475          return builder.build();
476        }
477    
478        private static final long serialVersionUID = 0;
479      }
480    
481      private final class InterfaceSet extends TypeSet {
482    
483        private transient final ImmutableSet<TypeToken<? super T>> interfaces;
484    
485        InterfaceSet(Iterable<TypeToken<? super T>> allTypes) {
486          this.interfaces = ImmutableSet.copyOf(Iterables.filter(allTypes, TypeFilter.INTERFACE_ONLY));
487        }
488    
489        @Override protected Set<TypeToken<? super T>> delegate() {
490          return interfaces;
491        }
492    
493        @Override public TypeSet interfaces() {
494          return this;
495        }
496    
497        @Override public TypeSet classes() {
498          throw new UnsupportedOperationException("interfaces().classes() not supported.");
499        }
500    
501        private Object readResolve() {
502          return getTypes().interfaces();
503        }
504    
505        private static final long serialVersionUID = 0;
506      }
507    
508      private final class ClassSet extends TypeSet {
509    
510        private transient final ImmutableSet<TypeToken<? super T>> classes = ImmutableSet.copyOf(
511            Iterators.filter(new AbstractSequentialIterator<TypeToken<? super T>>(
512                getRawType().isInterface() ? null : TypeToken.this) {
513              @Override protected TypeToken<? super T> computeNext(TypeToken<? super T> previous) {
514                return previous.getGenericSuperclass();
515              }
516            }, TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD));
517    
518        @Override protected Set<TypeToken<? super T>> delegate() {
519          return classes;
520        }
521    
522        @Override public TypeSet classes() {
523          return this;
524        }
525    
526        @Override public TypeSet interfaces() {
527          throw new UnsupportedOperationException("classes().interfaces() not supported.");
528        }
529    
530        private Object readResolve() {
531          return getTypes().classes();
532        }
533    
534        private static final long serialVersionUID = 0;
535      }
536    
537      private SortedSet<TypeToken<? super T>> findAllTypes() {
538        // type -> order number. 1 for Object, 2 for anything directly below, so on so forth.
539        Map<TypeToken<? super T>, Integer> map = Maps.newHashMap();
540        collectTypes(map);
541        return sortKeysByValue(map, Ordering.natural().reverse());
542      }
543    
544      /** Collects all types to map, and returns the total depth from T up to Object. */
545      private int collectTypes(Map<? super TypeToken<? super T>, Integer> map) {
546        Integer existing = map.get(this);
547        if (existing != null) {
548          // short circuit: if set contains type it already contains its supertypes
549          return existing;
550        }
551        int aboveMe = getRawType().isInterface()
552            ? 1 // interfaces should be listed before Object
553            : 0;
554        for (TypeToken<? super T> interfaceType : getGenericInterfaces()) {
555          aboveMe = Math.max(aboveMe, interfaceType.collectTypes(map));
556        }
557        TypeToken<? super T> superclass = getGenericSuperclass();
558        if (superclass != null) {
559          aboveMe = Math.max(aboveMe, superclass.collectTypes(map));
560        }
561        // TODO(benyu): should we include Object for interface?
562        // Also, CharSequence[] and Object[] for String[]?
563        map.put(this, aboveMe + 1);
564        return aboveMe + 1;
565      }
566    
567      private enum TypeFilter implements Predicate<TypeToken<?>> {
568    
569        IGNORE_TYPE_VARIABLE_OR_WILDCARD {
570          @Override public boolean apply(TypeToken<?> type) {
571            return !(type.runtimeType instanceof TypeVariable
572                || type.runtimeType instanceof WildcardType);
573          }
574        },
575        INTERFACE_ONLY {
576          @Override public boolean apply(TypeToken<?> type) {
577            return type.getRawType().isInterface();
578          }
579        }
580      }
581    
582      /**
583       * Returns true if {@code o} is another {@code TypeToken} that represents the same {@link Type}
584       * at runtime.
585       */
586      @Override public boolean equals(@Nullable Object o) {
587        if (o instanceof TypeToken) {
588          TypeToken<?> that = (TypeToken<?>) o;
589          return runtimeType.equals(that.runtimeType);
590        }
591        return false;
592      }
593    
594      @Override public int hashCode() {
595        return runtimeType.hashCode();
596      }
597    
598      @Override public String toString() {
599        return Types.toString(runtimeType);
600      }
601    
602      protected Object writeReplace() {
603        // TypeResolver just transforms the type to our own impls that are Serializable
604        // except TypeVariable.
605        return of(new TypeResolver().resolve(runtimeType));
606      }
607    
608      private static boolean isAssignable(Type from, Type to) {
609        if (to.equals(from)) {
610          return true;
611        }
612        if (to instanceof WildcardType) {
613          return isAssignableToWildcardType(from, (WildcardType) to);
614        }
615        // if "from" is type variable, it's assignable if any of its "extends"
616        // bounds is assignable to "to".
617        if (from instanceof TypeVariable) {
618          return isAssignableFromAny(((TypeVariable<?>) from).getBounds(), to);
619        }
620        // if "from" is wildcard, it'a assignable to "to" if any of its "extends"
621        // bounds is assignable to "to".
622        if (from instanceof WildcardType) {
623          return isAssignableFromAny(((WildcardType) from).getUpperBounds(), to);
624        }
625        if (from instanceof GenericArrayType) {
626          return isAssignableFromGenericArrayType((GenericArrayType) from, to);
627        }
628        // Proceed to regular Type assignability check
629        if (to instanceof Class) {
630          return isAssignableToClass(from, (Class<?>) to);
631        } else if (to instanceof ParameterizedType) {
632          return isAssignableToParameterizedType(from, (ParameterizedType) to);
633        } else if (to instanceof GenericArrayType) {
634          return isAssignableToGenericArrayType(from, (GenericArrayType) to);
635        } else { // to instanceof TypeVariable
636          return false;
637        }
638      }
639    
640      private static boolean isAssignableFromAny(Type[] fromTypes, Type to) {
641        for (Type from : fromTypes) {
642          if (isAssignable(from, to)) {
643            return true;
644          }
645        }
646        return false;
647      }
648    
649      private static boolean isAssignableToClass(Type from, Class<?> to) {
650        return to.isAssignableFrom(getRawType(from));
651      }
652    
653      private static boolean isAssignableToWildcardType(
654          Type from, WildcardType to) {
655        // if "to" is <? extends Foo>, "from" can be:
656        // Foo, SubFoo, <? extends Foo>, <? extends SubFoo>, <T extends Foo> or
657        // <T extends SubFoo>.
658        // if "to" is <? super Foo>, "from" can be:
659        // Foo, SuperFoo, <? super Foo> or <? super SuperFoo>.
660        return isAssignable(from, supertypeBound(to)) && isAssignableBySubtypeBound(from, to);
661      }
662    
663      private static boolean isAssignableBySubtypeBound(Type from, WildcardType to) {
664        Type toSubtypeBound = subtypeBound(to);
665        if (toSubtypeBound == null) {
666          return true;
667        }
668        Type fromSubtypeBound = subtypeBound(from);
669        if (fromSubtypeBound == null) {
670          return false;
671        }
672        return isAssignable(toSubtypeBound, fromSubtypeBound);
673      }
674    
675      private static boolean isAssignableToParameterizedType(Type from, ParameterizedType to) {
676        Class<?> matchedClass = getRawType(to);
677        if (!matchedClass.isAssignableFrom(getRawType(from))) {
678          return false;
679        }
680        Type[] typeParams = matchedClass.getTypeParameters();
681        Type[] toTypeArgs = to.getActualTypeArguments();
682        TypeToken<?> fromTypeToken = of(from);
683        for (int i = 0; i < typeParams.length; i++) {
684          // If "to" is "List<? extends CharSequence>"
685          // and "from" is StringArrayList,
686          // First step is to figure out StringArrayList "is-a" List<E> and <E> is
687          // String.
688          // typeParams[0] is E and fromTypeToken.get(typeParams[0]) will resolve to
689          // String.
690          // String is then matched against <? extends CharSequence>.
691          Type fromTypeArg = fromTypeToken.resolveType(typeParams[i]).runtimeType;
692          if (!matchTypeArgument(fromTypeArg, toTypeArgs[i])) {
693            return false;
694          }
695        }
696        return true;
697      }
698    
699      private static boolean isAssignableToGenericArrayType(Type from, GenericArrayType to) {
700        if (from instanceof Class) {
701          Class<?> fromClass = (Class<?>) from;
702          if (!fromClass.isArray()) {
703            return false;
704          }
705          return isAssignable(fromClass.getComponentType(), to.getGenericComponentType());
706        } else if (from instanceof GenericArrayType) {
707          GenericArrayType fromArrayType = (GenericArrayType) from;
708          return isAssignable(fromArrayType.getGenericComponentType(), to.getGenericComponentType());
709        } else {
710          return false;
711        }
712      }
713    
714      private static boolean isAssignableFromGenericArrayType(GenericArrayType from, Type to) {
715        if (to instanceof Class) {
716          Class<?> toClass = (Class<?>) to;
717          if (!toClass.isArray()) {
718            return toClass == Object.class; // any T[] is assignable to Object
719          }
720          return isAssignable(from.getGenericComponentType(), toClass.getComponentType());
721        } else if (to instanceof GenericArrayType) {
722          GenericArrayType toArrayType = (GenericArrayType) to;
723          return isAssignable(from.getGenericComponentType(), toArrayType.getGenericComponentType());
724        } else {
725          return false;
726        }
727      }
728    
729      private static boolean matchTypeArgument(Type from, Type to) {
730        if (from.equals(to)) {
731          return true;
732        }
733        if (to instanceof WildcardType) {
734          return isAssignableToWildcardType(from, (WildcardType) to);
735        }
736        return false;
737      }
738    
739      private static Type supertypeBound(Type type) {
740        if (type instanceof WildcardType) {
741          return supertypeBound((WildcardType) type);
742        }
743        return type;
744      }
745    
746      private static Type supertypeBound(WildcardType type) {
747        Type[] upperBounds = type.getUpperBounds();
748        if (upperBounds.length == 1) {
749          return supertypeBound(upperBounds[0]);
750        } else if (upperBounds.length == 0) {
751          return Object.class;
752        } else {
753          throw new AssertionError(
754              "There should be at most one upper bound for wildcard type: " + type);
755        }
756      }
757    
758      @Nullable private static Type subtypeBound(Type type) {
759        if (type instanceof WildcardType) {
760          return subtypeBound((WildcardType) type);
761        } else {
762          return type;
763        }
764      }
765    
766      @Nullable private static Type subtypeBound(WildcardType type) {
767        Type[] lowerBounds = type.getLowerBounds();
768        if (lowerBounds.length == 1) {
769          return subtypeBound(lowerBounds[0]);
770        } else if (lowerBounds.length == 0) {
771          return null;
772        } else {
773          throw new AssertionError(
774              "Wildcard should have at most one lower bound: " + type);
775        }
776      }
777    
778      @VisibleForTesting static Class<?> getRawType(Type type) {
779        if (type instanceof Class) {
780          return (Class<?>) type;
781        } else if (type instanceof ParameterizedType) {
782          ParameterizedType parameterizedType = (ParameterizedType) type;
783          // JDK implementation declares getRawType() to return Class<?>
784          return (Class<?>) parameterizedType.getRawType();
785        } else if (type instanceof GenericArrayType) {
786          GenericArrayType genericArrayType = (GenericArrayType) type;
787          return Types.getArrayClass(getRawType(genericArrayType.getGenericComponentType()));
788        } else if (type instanceof TypeVariable) {
789          // First bound is always the "primary" bound that determines the runtime signature.
790          return getRawType(((TypeVariable<?>) type).getBounds()[0]);
791        } else if (type instanceof WildcardType) {
792          // Wildcard can have one and only one upper bound.
793          return getRawType(((WildcardType) type).getUpperBounds()[0]);
794        } else {
795          throw new AssertionError(type + " unsupported");
796        }
797      }
798    
799      /**
800       * Returns the type token representing the generic type declaration of {@code cls}. For example:
801       * {@code TypeToken.getGenericType(Iterable.class)} returns {@code Iterable<T>}.
802       *
803       * <p>If {@code cls} isn't parameterized and isn't a generic array, the type token of the class is
804       * returned.
805       */
806      @VisibleForTesting static <T> TypeToken<? extends T> toGenericType(Class<T> cls) {
807        if (cls.isArray()) {
808          Type arrayOfGenericType = Types.newArrayType(
809              // If we are passed with int[].class, don't turn it to GenericArrayType
810              toGenericType(cls.getComponentType()).runtimeType);
811          @SuppressWarnings("unchecked") // array is covariant
812          TypeToken<? extends T> result = (TypeToken<? extends T>) of(arrayOfGenericType);
813          return result;
814        }
815        TypeVariable<Class<T>>[] typeParams = cls.getTypeParameters();
816        if (typeParams.length > 0) {
817          @SuppressWarnings("unchecked") // Like, it's Iterable<T> for Iterable.class
818          TypeToken<? extends T> type = (TypeToken<? extends T>)
819              of(Types.newParameterizedType(cls, typeParams));
820          return type;
821        } else {
822          return of(cls);
823        }
824      }
825    
826      private TypeToken<? super T> getSupertypeFromUpperBounds(
827          Class<? super T> supertype, Type[] upperBounds) {
828        for (Type upperBound : upperBounds) {
829          @SuppressWarnings("unchecked") // T's upperbound is <? super T>.
830          TypeToken<? super T> bound = (TypeToken<? super T>) of(upperBound);
831          if (of(supertype).isAssignableFrom(bound)) {
832            @SuppressWarnings({"rawtypes", "unchecked"}) // guarded by the isAssignableFrom check.
833            TypeToken<? super T> result = bound.getSupertype((Class) supertype);
834            return result;
835          }
836        }
837        throw new IllegalArgumentException(supertype + " isn't a super type of " + this);
838      }
839    
840      private TypeToken<? extends T> getSubtypeFromLowerBounds(Class<?> subclass, Type[] lowerBounds) {
841        for (Type lowerBound : lowerBounds) {
842          @SuppressWarnings("unchecked") // T's lower bound is <? extends T>
843          TypeToken<? extends T> bound = (TypeToken<? extends T>) of(lowerBound);
844          // Java supports only one lowerbound anyway.
845          return bound.getSubtype(subclass);
846        }
847        throw new IllegalArgumentException(subclass + " isn't a subclass of " + this);
848      }
849    
850      private TypeToken<? super T> getArraySupertype(Class<? super T> supertype) {
851        // with component type, we have lost generic type information
852        // Use raw type so that compiler allows us to call getSupertype()
853        @SuppressWarnings("rawtypes")
854        TypeToken componentType = checkNotNull(getComponentType(),
855            "%s isn't a super type of %s", supertype, this);
856        // array is covariant. component type is super type, so is the array type.
857        @SuppressWarnings("unchecked") // going from raw type back to generics
858        TypeToken<?> componentSupertype = componentType.getSupertype(supertype.getComponentType());
859        @SuppressWarnings("unchecked") // component type is super type, so is array type.
860        TypeToken<? super T> result = (TypeToken<? super T>)
861            // If we are passed with int[].class, don't turn it to GenericArrayType
862            of(newArrayClassOrGenericArrayType(componentSupertype.runtimeType));
863        return result;
864      }
865    
866      private TypeToken<? extends T> getArraySubtype(Class<?> subclass) {
867        // array is covariant. component type is subtype, so is the array type.
868        TypeToken<?> componentSubtype = getComponentType()
869            .getSubtype(subclass.getComponentType());
870        @SuppressWarnings("unchecked") // component type is subtype, so is array type.
871        TypeToken<? extends T> result = (TypeToken<? extends T>)
872            // If we are passed with int[].class, don't turn it to GenericArrayType
873            of(newArrayClassOrGenericArrayType(componentSubtype.runtimeType));
874        return result;
875      }
876    
877      private Type resolveTypeArgsForSubclass(Class<?> subclass) {
878        if (runtimeType instanceof Class) {
879          // no resolution needed
880          return subclass;
881        }
882        // class Base<A, B> {}
883        // class Sub<X, Y> extends Base<X, Y> {}
884        // Base<String, Integer>.subtype(Sub.class):
885    
886        // Sub<X, Y>.getSupertype(Base.class) => Base<X, Y>
887        // => X=String, Y=Integer
888        // => Sub<X, Y>=Sub<String, Integer>
889        TypeToken<?> genericSubtype = toGenericType(subclass);
890        @SuppressWarnings({"rawtypes", "unchecked"}) // subclass isn't <? extends T>
891        Type supertypeWithArgsFromSubtype = genericSubtype
892            .getSupertype((Class) getRawType())
893            .runtimeType;
894        return new TypeResolver().where(supertypeWithArgsFromSubtype, runtimeType)
895            .resolve(genericSubtype.runtimeType);
896      }
897    
898      /**
899       * Creates an array class if {@code componentType} is a class, or else, a
900       * {@link GenericArrayType}. This is what Java7 does for generic array type
901       * parameters.
902       */
903      private static Type newArrayClassOrGenericArrayType(Type componentType) {
904        return Types.JavaVersion.JAVA7.newArrayType(componentType);
905      }
906    
907      private static <K, V> ImmutableSortedSet<K> sortKeysByValue(
908          final Map<K, V> map, final Comparator<? super V> valueComparator) {
909        Comparator<K> keyComparator = new Comparator<K>() {
910          @Override public int compare(K left, K right) {
911            return valueComparator.compare(map.get(left), map.get(right));
912          }
913        };
914        return ImmutableSortedSet.copyOf(keyComparator, map.keySet());
915      }
916    
917      private static final class SimpleTypeToken<T> extends TypeToken<T> {
918    
919        SimpleTypeToken(Type type) {
920          super(type);
921        }
922    
923        private static final long serialVersionUID = 0;
924      }
925    }