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} while resolving free type variables in the context of 132 * {@code 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 represented type. */ 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 {@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 {@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 /** 423 * Returns true if this type is known to be an array type, such as {@code int[]}, {@code T[]}, 424 * {@code <? extends Map<String, Integer>[]>} etc. 425 */ 426 public final boolean isArray() { 427 return getComponentType() != null; 428 } 429 430 /** 431 * Returns the array component type if this type represents an array ({@code int[]}, {@code T[]}, 432 * {@code <? extends Map<String, Integer>[]>} etc.), or else {@code null} is returned. 433 */ 434 @Nullable public final TypeToken<?> getComponentType() { 435 Type componentType = Types.getComponentType(runtimeType); 436 if (componentType == null) { 437 return null; 438 } 439 return of(componentType); 440 } 441 442 /** 443 * The set of interfaces and classes that {@code T} is or is a subtype of. {@link Object} is not 444 * included in the set if this type is an interface. 445 */ 446 public class TypeSet extends ForwardingSet<TypeToken<? super T>> implements Serializable { 447 448 private transient ImmutableSet<TypeToken<? super T>> types; 449 450 TypeSet() {} 451 452 /** Returns the types that are interfaces implemented by this type. */ 453 public TypeSet interfaces() { 454 return new InterfaceSet(this); 455 } 456 457 /** Returns the types that are classes. */ 458 public TypeSet classes() { 459 return new ClassSet(); 460 } 461 462 @Override protected Set<TypeToken<? super T>> delegate() { 463 ImmutableSet<TypeToken<? super T>> filteredTypes = types; 464 if (filteredTypes == null) { 465 return (types = ImmutableSet.copyOf( 466 Sets.filter(findAllTypes(), TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD))); 467 } else { 468 return filteredTypes; 469 } 470 } 471 472 /** Returns the raw types of the types in this set, in the same order. */ 473 public final Set<Class<? super T>> rawTypes() { 474 ImmutableSet.Builder<Class<? super T>> builder = ImmutableSet.builder(); 475 for (TypeToken<? super T> type : this) { 476 builder.add(type.getRawType()); 477 } 478 return builder.build(); 479 } 480 481 private static final long serialVersionUID = 0; 482 } 483 484 private final class InterfaceSet extends TypeSet { 485 486 private transient final ImmutableSet<TypeToken<? super T>> interfaces; 487 488 InterfaceSet(Iterable<TypeToken<? super T>> allTypes) { 489 this.interfaces = ImmutableSet.copyOf(Iterables.filter(allTypes, TypeFilter.INTERFACE_ONLY)); 490 } 491 492 @Override protected Set<TypeToken<? super T>> delegate() { 493 return interfaces; 494 } 495 496 @Override public TypeSet interfaces() { 497 return this; 498 } 499 500 @Override public TypeSet classes() { 501 throw new UnsupportedOperationException("interfaces().classes() not supported."); 502 } 503 504 private Object readResolve() { 505 return getTypes().interfaces(); 506 } 507 508 private static final long serialVersionUID = 0; 509 } 510 511 private final class ClassSet extends TypeSet { 512 513 private transient final ImmutableSet<TypeToken<? super T>> classes = ImmutableSet.copyOf( 514 Iterators.filter(new AbstractSequentialIterator<TypeToken<? super T>>( 515 getRawType().isInterface() ? null : TypeToken.this) { 516 @Override protected TypeToken<? super T> computeNext(TypeToken<? super T> previous) { 517 return previous.getGenericSuperclass(); 518 } 519 }, TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)); 520 521 @Override protected Set<TypeToken<? super T>> delegate() { 522 return classes; 523 } 524 525 @Override public TypeSet classes() { 526 return this; 527 } 528 529 @Override public TypeSet interfaces() { 530 throw new UnsupportedOperationException("classes().interfaces() not supported."); 531 } 532 533 private Object readResolve() { 534 return getTypes().classes(); 535 } 536 537 private static final long serialVersionUID = 0; 538 } 539 540 private SortedSet<TypeToken<? super T>> findAllTypes() { 541 // type -> order number. 1 for Object, 2 for anything directly below, so on so forth. 542 Map<TypeToken<? super T>, Integer> map = Maps.newHashMap(); 543 collectTypes(map); 544 return sortKeysByValue(map, Ordering.natural().reverse()); 545 } 546 547 /** Collects all types to map, and returns the total depth from T up to Object. */ 548 private int collectTypes(Map<? super TypeToken<? super T>, Integer> map) { 549 Integer existing = map.get(this); 550 if (existing != null) { 551 // short circuit: if set contains type it already contains its supertypes 552 return existing; 553 } 554 int aboveMe = getRawType().isInterface() 555 ? 1 // interfaces should be listed before Object 556 : 0; 557 for (TypeToken<? super T> interfaceType : getGenericInterfaces()) { 558 aboveMe = Math.max(aboveMe, interfaceType.collectTypes(map)); 559 } 560 TypeToken<? super T> superclass = getGenericSuperclass(); 561 if (superclass != null) { 562 aboveMe = Math.max(aboveMe, superclass.collectTypes(map)); 563 } 564 // TODO(benyu): should we include Object for interface? 565 // Also, CharSequence[] and Object[] for String[]? 566 map.put(this, aboveMe + 1); 567 return aboveMe + 1; 568 } 569 570 private enum TypeFilter implements Predicate<TypeToken<?>> { 571 572 IGNORE_TYPE_VARIABLE_OR_WILDCARD { 573 @Override public boolean apply(TypeToken<?> type) { 574 return !(type.runtimeType instanceof TypeVariable 575 || type.runtimeType instanceof WildcardType); 576 } 577 }, 578 INTERFACE_ONLY { 579 @Override public boolean apply(TypeToken<?> type) { 580 return type.getRawType().isInterface(); 581 } 582 } 583 } 584 585 /** 586 * Returns true if {@code o} is another {@code TypeToken} that represents the same {@link Type}. 587 */ 588 @Override public boolean equals(@Nullable Object o) { 589 if (o instanceof TypeToken) { 590 TypeToken<?> that = (TypeToken<?>) o; 591 return runtimeType.equals(that.runtimeType); 592 } 593 return false; 594 } 595 596 @Override public int hashCode() { 597 return runtimeType.hashCode(); 598 } 599 600 @Override public String toString() { 601 return Types.toString(runtimeType); 602 } 603 604 /** Implemented to support serialization of subclasses. */ 605 protected Object writeReplace() { 606 // TypeResolver just transforms the type to our own impls that are Serializable 607 // except TypeVariable. 608 return of(new TypeResolver().resolve(runtimeType)); 609 } 610 611 private static boolean isAssignable(Type from, Type to) { 612 if (to.equals(from)) { 613 return true; 614 } 615 if (to instanceof WildcardType) { 616 return isAssignableToWildcardType(from, (WildcardType) to); 617 } 618 // if "from" is type variable, it's assignable if any of its "extends" 619 // bounds is assignable to "to". 620 if (from instanceof TypeVariable) { 621 return isAssignableFromAny(((TypeVariable<?>) from).getBounds(), to); 622 } 623 // if "from" is wildcard, it'a assignable to "to" if any of its "extends" 624 // bounds is assignable to "to". 625 if (from instanceof WildcardType) { 626 return isAssignableFromAny(((WildcardType) from).getUpperBounds(), to); 627 } 628 if (from instanceof GenericArrayType) { 629 return isAssignableFromGenericArrayType((GenericArrayType) from, to); 630 } 631 // Proceed to regular Type assignability check 632 if (to instanceof Class) { 633 return isAssignableToClass(from, (Class<?>) to); 634 } else if (to instanceof ParameterizedType) { 635 return isAssignableToParameterizedType(from, (ParameterizedType) to); 636 } else if (to instanceof GenericArrayType) { 637 return isAssignableToGenericArrayType(from, (GenericArrayType) to); 638 } else { // to instanceof TypeVariable 639 return false; 640 } 641 } 642 643 private static boolean isAssignableFromAny(Type[] fromTypes, Type to) { 644 for (Type from : fromTypes) { 645 if (isAssignable(from, to)) { 646 return true; 647 } 648 } 649 return false; 650 } 651 652 private static boolean isAssignableToClass(Type from, Class<?> to) { 653 return to.isAssignableFrom(getRawType(from)); 654 } 655 656 private static boolean isAssignableToWildcardType( 657 Type from, WildcardType to) { 658 // if "to" is <? extends Foo>, "from" can be: 659 // Foo, SubFoo, <? extends Foo>, <? extends SubFoo>, <T extends Foo> or 660 // <T extends SubFoo>. 661 // if "to" is <? super Foo>, "from" can be: 662 // Foo, SuperFoo, <? super Foo> or <? super SuperFoo>. 663 return isAssignable(from, supertypeBound(to)) && isAssignableBySubtypeBound(from, to); 664 } 665 666 private static boolean isAssignableBySubtypeBound(Type from, WildcardType to) { 667 Type toSubtypeBound = subtypeBound(to); 668 if (toSubtypeBound == null) { 669 return true; 670 } 671 Type fromSubtypeBound = subtypeBound(from); 672 if (fromSubtypeBound == null) { 673 return false; 674 } 675 return isAssignable(toSubtypeBound, fromSubtypeBound); 676 } 677 678 private static boolean isAssignableToParameterizedType(Type from, ParameterizedType to) { 679 Class<?> matchedClass = getRawType(to); 680 if (!matchedClass.isAssignableFrom(getRawType(from))) { 681 return false; 682 } 683 Type[] typeParams = matchedClass.getTypeParameters(); 684 Type[] toTypeArgs = to.getActualTypeArguments(); 685 TypeToken<?> fromTypeToken = of(from); 686 for (int i = 0; i < typeParams.length; i++) { 687 // If "to" is "List<? extends CharSequence>" 688 // and "from" is StringArrayList, 689 // First step is to figure out StringArrayList "is-a" List<E> and <E> is 690 // String. 691 // typeParams[0] is E and fromTypeToken.get(typeParams[0]) will resolve to 692 // String. 693 // String is then matched against <? extends CharSequence>. 694 Type fromTypeArg = fromTypeToken.resolveType(typeParams[i]).runtimeType; 695 if (!matchTypeArgument(fromTypeArg, toTypeArgs[i])) { 696 return false; 697 } 698 } 699 return true; 700 } 701 702 private static boolean isAssignableToGenericArrayType(Type from, GenericArrayType to) { 703 if (from instanceof Class) { 704 Class<?> fromClass = (Class<?>) from; 705 if (!fromClass.isArray()) { 706 return false; 707 } 708 return isAssignable(fromClass.getComponentType(), to.getGenericComponentType()); 709 } else if (from instanceof GenericArrayType) { 710 GenericArrayType fromArrayType = (GenericArrayType) from; 711 return isAssignable(fromArrayType.getGenericComponentType(), to.getGenericComponentType()); 712 } else { 713 return false; 714 } 715 } 716 717 private static boolean isAssignableFromGenericArrayType(GenericArrayType from, Type to) { 718 if (to instanceof Class) { 719 Class<?> toClass = (Class<?>) to; 720 if (!toClass.isArray()) { 721 return toClass == Object.class; // any T[] is assignable to Object 722 } 723 return isAssignable(from.getGenericComponentType(), toClass.getComponentType()); 724 } else if (to instanceof GenericArrayType) { 725 GenericArrayType toArrayType = (GenericArrayType) to; 726 return isAssignable(from.getGenericComponentType(), toArrayType.getGenericComponentType()); 727 } else { 728 return false; 729 } 730 } 731 732 private static boolean matchTypeArgument(Type from, Type to) { 733 if (from.equals(to)) { 734 return true; 735 } 736 if (to instanceof WildcardType) { 737 return isAssignableToWildcardType(from, (WildcardType) to); 738 } 739 return false; 740 } 741 742 private static Type supertypeBound(Type type) { 743 if (type instanceof WildcardType) { 744 return supertypeBound((WildcardType) type); 745 } 746 return type; 747 } 748 749 private static Type supertypeBound(WildcardType type) { 750 Type[] upperBounds = type.getUpperBounds(); 751 if (upperBounds.length == 1) { 752 return supertypeBound(upperBounds[0]); 753 } else if (upperBounds.length == 0) { 754 return Object.class; 755 } else { 756 throw new AssertionError( 757 "There should be at most one upper bound for wildcard type: " + type); 758 } 759 } 760 761 @Nullable private static Type subtypeBound(Type type) { 762 if (type instanceof WildcardType) { 763 return subtypeBound((WildcardType) type); 764 } else { 765 return type; 766 } 767 } 768 769 @Nullable private static Type subtypeBound(WildcardType type) { 770 Type[] lowerBounds = type.getLowerBounds(); 771 if (lowerBounds.length == 1) { 772 return subtypeBound(lowerBounds[0]); 773 } else if (lowerBounds.length == 0) { 774 return null; 775 } else { 776 throw new AssertionError( 777 "Wildcard should have at most one lower bound: " + type); 778 } 779 } 780 781 @VisibleForTesting static Class<?> getRawType(Type type) { 782 if (type instanceof Class) { 783 return (Class<?>) type; 784 } else if (type instanceof ParameterizedType) { 785 ParameterizedType parameterizedType = (ParameterizedType) type; 786 // JDK implementation declares getRawType() to return Class<?> 787 return (Class<?>) parameterizedType.getRawType(); 788 } else if (type instanceof GenericArrayType) { 789 GenericArrayType genericArrayType = (GenericArrayType) type; 790 return Types.getArrayClass(getRawType(genericArrayType.getGenericComponentType())); 791 } else if (type instanceof TypeVariable) { 792 // First bound is always the "primary" bound that determines the runtime signature. 793 return getRawType(((TypeVariable<?>) type).getBounds()[0]); 794 } else if (type instanceof WildcardType) { 795 // Wildcard can have one and only one upper bound. 796 return getRawType(((WildcardType) type).getUpperBounds()[0]); 797 } else { 798 throw new AssertionError(type + " unsupported"); 799 } 800 } 801 802 /** 803 * Returns the type token representing the generic type declaration of {@code cls}. For example: 804 * {@code TypeToken.getGenericType(Iterable.class)} returns {@code Iterable<T>}. 805 * 806 * <p>If {@code cls} isn't parameterized and isn't a generic array, the type token of the class is 807 * returned. 808 */ 809 @VisibleForTesting static <T> TypeToken<? extends T> toGenericType(Class<T> cls) { 810 if (cls.isArray()) { 811 Type arrayOfGenericType = Types.newArrayType( 812 // If we are passed with int[].class, don't turn it to GenericArrayType 813 toGenericType(cls.getComponentType()).runtimeType); 814 @SuppressWarnings("unchecked") // array is covariant 815 TypeToken<? extends T> result = (TypeToken<? extends T>) of(arrayOfGenericType); 816 return result; 817 } 818 TypeVariable<Class<T>>[] typeParams = cls.getTypeParameters(); 819 if (typeParams.length > 0) { 820 @SuppressWarnings("unchecked") // Like, it's Iterable<T> for Iterable.class 821 TypeToken<? extends T> type = (TypeToken<? extends T>) 822 of(Types.newParameterizedType(cls, typeParams)); 823 return type; 824 } else { 825 return of(cls); 826 } 827 } 828 829 private TypeToken<? super T> getSupertypeFromUpperBounds( 830 Class<? super T> supertype, Type[] upperBounds) { 831 for (Type upperBound : upperBounds) { 832 @SuppressWarnings("unchecked") // T's upperbound is <? super T>. 833 TypeToken<? super T> bound = (TypeToken<? super T>) of(upperBound); 834 if (of(supertype).isAssignableFrom(bound)) { 835 @SuppressWarnings({"rawtypes", "unchecked"}) // guarded by the isAssignableFrom check. 836 TypeToken<? super T> result = bound.getSupertype((Class) supertype); 837 return result; 838 } 839 } 840 throw new IllegalArgumentException(supertype + " isn't a super type of " + this); 841 } 842 843 private TypeToken<? extends T> getSubtypeFromLowerBounds(Class<?> subclass, Type[] lowerBounds) { 844 for (Type lowerBound : lowerBounds) { 845 @SuppressWarnings("unchecked") // T's lower bound is <? extends T> 846 TypeToken<? extends T> bound = (TypeToken<? extends T>) of(lowerBound); 847 // Java supports only one lowerbound anyway. 848 return bound.getSubtype(subclass); 849 } 850 throw new IllegalArgumentException(subclass + " isn't a subclass of " + this); 851 } 852 853 private TypeToken<? super T> getArraySupertype(Class<? super T> supertype) { 854 // with component type, we have lost generic type information 855 // Use raw type so that compiler allows us to call getSupertype() 856 @SuppressWarnings("rawtypes") 857 TypeToken componentType = checkNotNull(getComponentType(), 858 "%s isn't a super type of %s", supertype, this); 859 // array is covariant. component type is super type, so is the array type. 860 @SuppressWarnings("unchecked") // going from raw type back to generics 861 TypeToken<?> componentSupertype = componentType.getSupertype(supertype.getComponentType()); 862 @SuppressWarnings("unchecked") // component type is super type, so is array type. 863 TypeToken<? super T> result = (TypeToken<? super T>) 864 // If we are passed with int[].class, don't turn it to GenericArrayType 865 of(newArrayClassOrGenericArrayType(componentSupertype.runtimeType)); 866 return result; 867 } 868 869 private TypeToken<? extends T> getArraySubtype(Class<?> subclass) { 870 // array is covariant. component type is subtype, so is the array type. 871 TypeToken<?> componentSubtype = getComponentType() 872 .getSubtype(subclass.getComponentType()); 873 @SuppressWarnings("unchecked") // component type is subtype, so is array type. 874 TypeToken<? extends T> result = (TypeToken<? extends T>) 875 // If we are passed with int[].class, don't turn it to GenericArrayType 876 of(newArrayClassOrGenericArrayType(componentSubtype.runtimeType)); 877 return result; 878 } 879 880 private Type resolveTypeArgsForSubclass(Class<?> subclass) { 881 if (runtimeType instanceof Class) { 882 // no resolution needed 883 return subclass; 884 } 885 // class Base<A, B> {} 886 // class Sub<X, Y> extends Base<X, Y> {} 887 // Base<String, Integer>.subtype(Sub.class): 888 889 // Sub<X, Y>.getSupertype(Base.class) => Base<X, Y> 890 // => X=String, Y=Integer 891 // => Sub<X, Y>=Sub<String, Integer> 892 TypeToken<?> genericSubtype = toGenericType(subclass); 893 @SuppressWarnings({"rawtypes", "unchecked"}) // subclass isn't <? extends T> 894 Type supertypeWithArgsFromSubtype = genericSubtype 895 .getSupertype((Class) getRawType()) 896 .runtimeType; 897 return new TypeResolver().where(supertypeWithArgsFromSubtype, runtimeType) 898 .resolve(genericSubtype.runtimeType); 899 } 900 901 /** 902 * Creates an array class if {@code componentType} is a class, or else, a 903 * {@link GenericArrayType}. This is what Java7 does for generic array type 904 * parameters. 905 */ 906 private static Type newArrayClassOrGenericArrayType(Type componentType) { 907 return Types.JavaVersion.JAVA7.newArrayType(componentType); 908 } 909 910 private static <K, V> ImmutableSortedSet<K> sortKeysByValue( 911 final Map<K, V> map, final Comparator<? super V> valueComparator) { 912 Comparator<K> keyComparator = new Comparator<K>() { 913 @Override public int compare(K left, K right) { 914 return valueComparator.compare(map.get(left), map.get(right)); 915 } 916 }; 917 return ImmutableSortedSet.copyOf(keyComparator, map.keySet()); 918 } 919 920 private static final class SimpleTypeToken<T> extends TypeToken<T> { 921 922 SimpleTypeToken(Type type) { 923 super(type); 924 } 925 926 private static final long serialVersionUID = 0; 927 } 928 }