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