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