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