001/* 002 * Copyright (C) 2006 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.reflect; 018 019import static com.google.common.base.Preconditions.checkArgument; 020import static com.google.common.base.Preconditions.checkNotNull; 021import static com.google.common.base.Preconditions.checkState; 022 023import com.google.common.annotations.Beta; 024import com.google.common.annotations.VisibleForTesting; 025import com.google.common.base.Predicate; 026import com.google.common.collect.FluentIterable; 027import com.google.common.collect.ForwardingSet; 028import com.google.common.collect.ImmutableList; 029import com.google.common.collect.ImmutableMap; 030import com.google.common.collect.ImmutableSet; 031import com.google.common.collect.Maps; 032import com.google.common.collect.Ordering; 033 034import java.io.Serializable; 035import java.lang.reflect.Constructor; 036import java.lang.reflect.GenericArrayType; 037import java.lang.reflect.Method; 038import java.lang.reflect.ParameterizedType; 039import java.lang.reflect.Type; 040import java.lang.reflect.TypeVariable; 041import java.lang.reflect.WildcardType; 042import java.util.Arrays; 043import java.util.Comparator; 044import java.util.Map; 045import java.util.Set; 046 047import javax.annotation.Nullable; 048 049/** 050 * A {@link Type} with generics. 051 * 052 * <p>Operations that are otherwise only available in {@link Class} are implemented to support 053 * {@code Type}, for example {@link #isAssignableFrom}, {@link #isArray} and {@link 054 * #getComponentType}. It also provides additional utilities such as {@link #getTypes} and {@link 055 * #resolveType} etc. 056 * 057 * <p>There are three ways to get a {@code TypeToken} instance: <ul> 058 * <li>Wrap a {@code Type} obtained via reflection. For example: {@code 059 * TypeToken.of(method.getGenericReturnType())}. 060 * <li>Capture a generic type with a (usually anonymous) subclass. For example: <pre> {@code 061 * 062 * new TypeToken<List<String>>() {} 063 * }</pre> 064 * Note that it's critical that the actual type argument is carried by a subclass. 065 * The following code is wrong because it only captures the {@code <T>} type variable 066 * of the {@code listType()} method signature; while {@code <String>} is lost in erasure: 067 * <pre> {@code 068 * 069 * class Util { 070 * static <T> TypeToken<List<T>> listType() { 071 * return new TypeToken<List<T>>() {}; 072 * } 073 * } 074 * 075 * TypeToken<List<String>> stringListType = Util.<String>listType(); 076 * }</pre> 077 * <li>Capture a generic type with a (usually anonymous) subclass and resolve it against 078 * a context class that knows what the type parameters are. For example: <pre> {@code 079 * abstract class IKnowMyType<T> { 080 * TypeToken<T> type = new TypeToken<T>(getClass()) {}; 081 * } 082 * new IKnowMyType<String>() {}.type => String 083 * }</pre> 084 * </ul> 085 * 086 * <p>{@code TypeToken} is serializable when no type variable is contained in the type. 087 * 088 * <p>Note to Guice users: {@code} TypeToken is similar to Guice's {@code TypeLiteral} class, 089 * but with one important difference: it supports non-reified types such as {@code T}, 090 * {@code List<T>} or even {@code List<? extends Number>}; while TypeLiteral does not. 091 * TypeToken is also serializable and offers numerous additional utility methods. 092 * 093 * @author Bob Lee 094 * @author Sven Mawson 095 * @author Ben Yu 096 * @since 12.0 097 */ 098@Beta 099@SuppressWarnings("serial") // SimpleTypeToken is the serialized form. 100public abstract class TypeToken<T> extends TypeCapture<T> implements Serializable { 101 102 private final Type runtimeType; 103 104 /** Resolver for resolving types with {@link #runtimeType} as context. */ 105 private transient TypeResolver typeResolver; 106 107 /** 108 * Constructs a new type token of {@code T}. 109 * 110 * <p>Clients create an empty anonymous subclass. Doing so embeds the type 111 * parameter in the anonymous class's type hierarchy so we can reconstitute 112 * it at runtime despite erasure. 113 * 114 * <p>For example: <pre> {@code 115 * 116 * TypeToken<List<String>> t = new TypeToken<List<String>>() {}; 117 * }</pre> 118 */ 119 protected TypeToken() { 120 this.runtimeType = capture(); 121 checkState(!(runtimeType instanceof TypeVariable), 122 "Cannot construct a TypeToken for a type variable.\n" + 123 "You probably meant to call new TypeToken<%s>(getClass()) " + 124 "that can resolve the type variable for you.\n" + 125 "If you do need to create a TypeToken of a type variable, " + 126 "please use TypeToken.of() instead.", runtimeType); 127 } 128 129 /** 130 * Constructs a new type token of {@code T} while resolving free type variables in the context of 131 * {@code declaringClass}. 132 * 133 * <p>Clients create an empty anonymous subclass. Doing so embeds the type 134 * parameter in the anonymous class's type hierarchy so we can reconstitute 135 * it at runtime despite erasure. 136 * 137 * <p>For example: <pre> {@code 138 * 139 * abstract class IKnowMyType<T> { 140 * TypeToken<T> getMyType() { 141 * return new TypeToken<T>(getClass()) {}; 142 * } 143 * } 144 * 145 * new IKnowMyType<String>() {}.getMyType() => String 146 * }</pre> 147 */ 148 protected TypeToken(Class<?> declaringClass) { 149 Type captured = super.capture(); 150 if (captured instanceof Class) { 151 this.runtimeType = captured; 152 } else { 153 this.runtimeType = of(declaringClass).resolveType(captured).runtimeType; 154 } 155 } 156 157 private TypeToken(Type type) { 158 this.runtimeType = checkNotNull(type); 159 } 160 161 /** Returns an instance of type token that wraps {@code type}. */ 162 public static <T> TypeToken<T> of(Class<T> type) { 163 return new SimpleTypeToken<T>(type); 164 } 165 166 /** Returns an instance of type token that wraps {@code type}. */ 167 public static TypeToken<?> of(Type type) { 168 return new SimpleTypeToken<Object>(type); 169 } 170 171 /** 172 * Returns the raw type of {@code T}. Formally speaking, if {@code T} is returned by 173 * {@link java.lang.reflect.Method#getGenericReturnType}, the raw type is what's returned by 174 * {@link java.lang.reflect.Method#getReturnType} of the same method object. Specifically: 175 * <ul> 176 * <li>If {@code T} is a {@code Class} itself, {@code T} itself is returned. 177 * <li>If {@code T} is a {@link ParameterizedType}, the raw type of the parameterized type is 178 * returned. 179 * <li>If {@code T} is a {@link GenericArrayType}, the returned type is the corresponding array 180 * class. For example: {@code List<Integer>[] => List[]}. 181 * <li>If {@code T} is a type variable or a wildcard type, the raw type of the first upper bound 182 * is returned. For example: {@code <X extends Foo> => Foo}. 183 * </ul> 184 */ 185 public final Class<? super T> getRawType() { 186 Class<?> rawType = getRawType(runtimeType); 187 @SuppressWarnings("unchecked") // raw type is |T| 188 Class<? super T> result = (Class<? super T>) rawType; 189 return result; 190 } 191 192 /** 193 * Returns the raw type of the class or parameterized type; if {@code T} is type variable or 194 * wildcard type, the raw types of all its upper bounds are returned. 195 */ 196 private ImmutableSet<Class<? super T>> getImmediateRawTypes() { 197 // Cast from ImmutableSet<Class<?>> to ImmutableSet<Class<? super T>> 198 @SuppressWarnings({"unchecked", "rawtypes"}) 199 ImmutableSet<Class<? super T>> result = (ImmutableSet) getRawTypes(runtimeType); 200 return result; 201 } 202 203 /** Returns the represented type. */ 204 public final Type getType() { 205 return runtimeType; 206 } 207 208 /** 209 * Returns a new {@code TypeToken} where type variables represented by {@code typeParam} 210 * are substituted by {@code typeArg}. For example, it can be used to construct 211 * {@code Map<K, V>} for any {@code K} and {@code V} type: <pre> {@code 212 * 213 * static <K, V> TypeToken<Map<K, V>> mapOf( 214 * TypeToken<K> keyType, TypeToken<V> valueType) { 215 * return new TypeToken<Map<K, V>>() {} 216 * .where(new TypeParameter<K>() {}, keyType) 217 * .where(new TypeParameter<V>() {}, valueType); 218 * } 219 * }</pre> 220 * 221 * @param <X> The parameter type 222 * @param typeParam the parameter type variable 223 * @param typeArg the actual type to substitute 224 */ 225 public final <X> TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg) { 226 TypeResolver resolver = new TypeResolver() 227 .where(ImmutableMap.of(typeParam.typeVariable, typeArg.runtimeType)); 228 // If there's any type error, we'd report now rather than later. 229 return new SimpleTypeToken<T>(resolver.resolveType(runtimeType)); 230 } 231 232 /** 233 * Returns a new {@code TypeToken} where type variables represented by {@code typeParam} 234 * are substituted by {@code typeArg}. For example, it can be used to construct 235 * {@code Map<K, V>} for any {@code K} and {@code V} type: <pre> {@code 236 * 237 * static <K, V> TypeToken<Map<K, V>> mapOf( 238 * Class<K> keyType, Class<V> valueType) { 239 * return new TypeToken<Map<K, V>>() {} 240 * .where(new TypeParameter<K>() {}, keyType) 241 * .where(new TypeParameter<V>() {}, valueType); 242 * } 243 * }</pre> 244 * 245 * @param <X> The parameter type 246 * @param typeParam the parameter type variable 247 * @param typeArg the actual type to substitute 248 */ 249 public final <X> TypeToken<T> where(TypeParameter<X> typeParam, Class<X> typeArg) { 250 return where(typeParam, of(typeArg)); 251 } 252 253 /** 254 * Resolves the given {@code type} against the type context represented by this type. 255 * For example: <pre> {@code 256 * 257 * new TypeToken<List<String>>() {}.resolveType( 258 * List.class.getMethod("get", int.class).getGenericReturnType()) 259 * => String.class 260 * }</pre> 261 */ 262 public final TypeToken<?> resolveType(Type type) { 263 checkNotNull(type); 264 TypeResolver resolver = typeResolver; 265 if (resolver == null) { 266 resolver = (typeResolver = TypeResolver.accordingTo(runtimeType)); 267 } 268 return of(resolver.resolveType(type)); 269 } 270 271 private Type[] resolveInPlace(Type[] types) { 272 for (int i = 0; i < types.length; i++) { 273 types[i] = resolveType(types[i]).getType(); 274 } 275 return types; 276 } 277 278 private TypeToken<?> resolveSupertype(Type type) { 279 TypeToken<?> supertype = resolveType(type); 280 // super types' type mapping is a subset of type mapping of this type. 281 supertype.typeResolver = typeResolver; 282 return supertype; 283 } 284 285 /** 286 * Returns the generic superclass of this type or {@code null} if the type represents 287 * {@link Object} or an interface. This method is similar but different from {@link 288 * Class#getGenericSuperclass}. For example, {@code 289 * new TypeToken<StringArrayList>() {}.getGenericSuperclass()} will return {@code 290 * new TypeToken<ArrayList<String>>() {}}; while {@code 291 * StringArrayList.class.getGenericSuperclass()} will return {@code ArrayList<E>}, where {@code E} 292 * is the type variable declared by class {@code ArrayList}. 293 * 294 * <p>If this type is a type variable or wildcard, its first upper bound is examined and returned 295 * if the bound is a class or extends from a class. This means that the returned type could be a 296 * type variable too. 297 */ 298 @Nullable 299 final TypeToken<? super T> getGenericSuperclass() { 300 if (runtimeType instanceof TypeVariable) { 301 // First bound is always the super class, if one exists. 302 return boundAsSuperclass(((TypeVariable<?>) runtimeType).getBounds()[0]); 303 } 304 if (runtimeType instanceof WildcardType) { 305 // wildcard has one and only one upper bound. 306 return boundAsSuperclass(((WildcardType) runtimeType).getUpperBounds()[0]); 307 } 308 Type superclass = getRawType().getGenericSuperclass(); 309 if (superclass == null) { 310 return null; 311 } 312 @SuppressWarnings("unchecked") // super class of T 313 TypeToken<? super T> superToken = (TypeToken<? super T>) resolveSupertype(superclass); 314 return superToken; 315 } 316 317 @Nullable private TypeToken<? super T> boundAsSuperclass(Type bound) { 318 TypeToken<?> token = of(bound); 319 if (token.getRawType().isInterface()) { 320 return null; 321 } 322 @SuppressWarnings("unchecked") // only upper bound of T is passed in. 323 TypeToken<? super T> superclass = (TypeToken<? super T>) token; 324 return superclass; 325 } 326 327 /** 328 * Returns the generic interfaces that this type directly {@code implements}. This method is 329 * similar but different from {@link Class#getGenericInterfaces()}. For example, {@code 330 * new TypeToken<List<String>>() {}.getGenericInterfaces()} will return a list that contains 331 * {@code new TypeToken<Iterable<String>>() {}}; while {@code List.class.getGenericInterfaces()} 332 * will return an array that contains {@code Iterable<T>}, where the {@code T} is the type 333 * variable declared by interface {@code Iterable}. 334 * 335 * <p>If this type is a type variable or wildcard, its upper bounds are examined and those that 336 * are either an interface or upper-bounded only by interfaces are returned. This means that the 337 * returned types could include type variables too. 338 */ 339 final ImmutableList<TypeToken<? super T>> getGenericInterfaces() { 340 if (runtimeType instanceof TypeVariable) { 341 return boundsAsInterfaces(((TypeVariable<?>) runtimeType).getBounds()); 342 } 343 if (runtimeType instanceof WildcardType) { 344 return boundsAsInterfaces(((WildcardType) runtimeType).getUpperBounds()); 345 } 346 ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder(); 347 for (Type interfaceType : getRawType().getGenericInterfaces()) { 348 @SuppressWarnings("unchecked") // interface of T 349 TypeToken<? super T> resolvedInterface = (TypeToken<? super T>) 350 resolveSupertype(interfaceType); 351 builder.add(resolvedInterface); 352 } 353 return builder.build(); 354 } 355 356 private ImmutableList<TypeToken<? super T>> boundsAsInterfaces(Type[] bounds) { 357 ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder(); 358 for (Type bound : bounds) { 359 @SuppressWarnings("unchecked") // upper bound of T 360 TypeToken<? super T> boundType = (TypeToken<? super T>) of(bound); 361 if (boundType.getRawType().isInterface()) { 362 builder.add(boundType); 363 } 364 } 365 return builder.build(); 366 } 367 368 /** 369 * Returns the set of interfaces and classes that this type is or is a subtype of. The returned 370 * types are parameterized with proper type arguments. 371 * 372 * <p>Subtypes are always listed before supertypes. But the reverse is not true. A type isn't 373 * necessarily a subtype of all the types following. Order between types without subtype 374 * relationship is arbitrary and not guaranteed. 375 * 376 * <p>If this type is a type variable or wildcard, upper bounds that are themselves type variables 377 * aren't included (their super interfaces and superclasses are). 378 */ 379 public final TypeSet getTypes() { 380 return new TypeSet(); 381 } 382 383 /** 384 * Returns the generic form of {@code superclass}. For example, if this is 385 * {@code ArrayList<String>}, {@code Iterable<String>} is returned given the 386 * input {@code Iterable.class}. 387 */ 388 public final TypeToken<? super T> getSupertype(Class<? super T> superclass) { 389 checkArgument(superclass.isAssignableFrom(getRawType()), 390 "%s is not a super class of %s", superclass, this); 391 if (runtimeType instanceof TypeVariable) { 392 return getSupertypeFromUpperBounds(superclass, ((TypeVariable<?>) runtimeType).getBounds()); 393 } 394 if (runtimeType instanceof WildcardType) { 395 return getSupertypeFromUpperBounds(superclass, ((WildcardType) runtimeType).getUpperBounds()); 396 } 397 if (superclass.isArray()) { 398 return getArraySupertype(superclass); 399 } 400 @SuppressWarnings("unchecked") // resolved supertype 401 TypeToken<? super T> supertype = (TypeToken<? super T>) 402 resolveSupertype(toGenericType(superclass).runtimeType); 403 return supertype; 404 } 405 406 /** 407 * Returns subtype of {@code this} with {@code subclass} as the raw class. 408 * For example, if this is {@code Iterable<String>} and {@code subclass} is {@code List}, 409 * {@code List<String>} is returned. 410 */ 411 public final TypeToken<? extends T> getSubtype(Class<?> subclass) { 412 checkArgument(!(runtimeType instanceof TypeVariable), 413 "Cannot get subtype of type variable <%s>", this); 414 if (runtimeType instanceof WildcardType) { 415 return getSubtypeFromLowerBounds(subclass, ((WildcardType) runtimeType).getLowerBounds()); 416 } 417 checkArgument(getRawType().isAssignableFrom(subclass), 418 "%s isn't a subclass of %s", subclass, this); 419 // unwrap array type if necessary 420 if (isArray()) { 421 return getArraySubtype(subclass); 422 } 423 @SuppressWarnings("unchecked") // guarded by the isAssignableFrom() statement above 424 TypeToken<? extends T> subtype = (TypeToken<? extends T>) 425 of(resolveTypeArgsForSubclass(subclass)); 426 return subtype; 427 } 428 429 /** Returns true if this type is assignable from the given {@code type}. */ 430 public final boolean isAssignableFrom(TypeToken<?> type) { 431 return isAssignableFrom(type.runtimeType); 432 } 433 434 /** Check if this type is assignable from the given {@code type}. */ 435 public final boolean isAssignableFrom(Type type) { 436 return isAssignable(checkNotNull(type), runtimeType); 437 } 438 439 /** 440 * Returns true if this type is known to be an array type, such as {@code int[]}, {@code T[]}, 441 * {@code <? extends Map<String, Integer>[]>} etc. 442 */ 443 public final boolean isArray() { 444 return getComponentType() != null; 445 } 446 447 /** 448 * Returns the array component type if this type represents an array ({@code int[]}, {@code T[]}, 449 * {@code <? extends Map<String, Integer>[]>} etc.), or else {@code null} is returned. 450 */ 451 @Nullable public final TypeToken<?> getComponentType() { 452 Type componentType = Types.getComponentType(runtimeType); 453 if (componentType == null) { 454 return null; 455 } 456 return of(componentType); 457 } 458 459 /** 460 * Returns the {@link Invokable} for {@code method}, which must be a member of {@code T}. 461 * 462 * @since 14.0 463 */ 464 public final Invokable<T, Object> method(Method method) { 465 checkArgument(of(method.getDeclaringClass()).isAssignableFrom(this), 466 "%s not declared by %s", method, this); 467 return new Invokable.MethodInvokable<T>(method) { 468 @Override Type getGenericReturnType() { 469 return resolveType(super.getGenericReturnType()).getType(); 470 } 471 @Override Type[] getGenericParameterTypes() { 472 return resolveInPlace(super.getGenericParameterTypes()); 473 } 474 @Override Type[] getGenericExceptionTypes() { 475 return resolveInPlace(super.getGenericExceptionTypes()); 476 } 477 @Override public TypeToken<T> getOwnerType() { 478 return TypeToken.this; 479 } 480 }; 481 } 482 483 /** 484 * Returns the {@link Invokable} for {@code constructor}, which must be a member of {@code T}. 485 * 486 * @since 14.0 487 */ 488 public final Invokable<T, T> constructor(Constructor<?> constructor) { 489 checkArgument(constructor.getDeclaringClass() == getRawType(), 490 "%s not declared by %s", constructor, getRawType()); 491 return new Invokable.ConstructorInvokable<T>(constructor) { 492 @Override Type getGenericReturnType() { 493 return resolveType(super.getGenericReturnType()).getType(); 494 } 495 @Override Type[] getGenericParameterTypes() { 496 return resolveInPlace(super.getGenericParameterTypes()); 497 } 498 @Override Type[] getGenericExceptionTypes() { 499 return resolveInPlace(super.getGenericExceptionTypes()); 500 } 501 @Override public TypeToken<T> getOwnerType() { 502 return TypeToken.this; 503 } 504 }; 505 } 506 507 /** 508 * The set of interfaces and classes that {@code T} is or is a subtype of. {@link Object} is not 509 * included in the set if this type is an interface. 510 */ 511 public class TypeSet extends ForwardingSet<TypeToken<? super T>> implements Serializable { 512 513 private transient ImmutableSet<TypeToken<? super T>> types; 514 515 TypeSet() {} 516 517 /** Returns the types that are interfaces implemented by this type. */ 518 public TypeSet interfaces() { 519 return new InterfaceSet(this); 520 } 521 522 /** Returns the types that are classes. */ 523 public TypeSet classes() { 524 return new ClassSet(); 525 } 526 527 @Override protected Set<TypeToken<? super T>> delegate() { 528 ImmutableSet<TypeToken<? super T>> filteredTypes = types; 529 if (filteredTypes == null) { 530 // Java has no way to express ? super T when we parameterize TypeToken vs. Class. 531 @SuppressWarnings({"unchecked", "rawtypes"}) 532 ImmutableList<TypeToken<? super T>> collectedTypes = (ImmutableList) 533 TypeCollector.FOR_GENERIC_TYPE.collectTypes(TypeToken.this); 534 return (types = FluentIterable.from(collectedTypes) 535 .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD) 536 .toSet()); 537 } else { 538 return filteredTypes; 539 } 540 } 541 542 /** Returns the raw types of the types in this set, in the same order. */ 543 public Set<Class<? super T>> rawTypes() { 544 // Java has no way to express ? super T when we parameterize TypeToken vs. Class. 545 @SuppressWarnings({"unchecked", "rawtypes"}) 546 ImmutableList<Class<? super T>> collectedTypes = (ImmutableList) 547 TypeCollector.FOR_RAW_TYPE.collectTypes(getImmediateRawTypes()); 548 return ImmutableSet.copyOf(collectedTypes); 549 } 550 551 private static final long serialVersionUID = 0; 552 } 553 554 private final class InterfaceSet extends TypeSet { 555 556 private transient final TypeSet allTypes; 557 private transient ImmutableSet<TypeToken<? super T>> interfaces; 558 559 InterfaceSet(TypeSet allTypes) { 560 this.allTypes = allTypes; 561 } 562 563 @Override protected Set<TypeToken<? super T>> delegate() { 564 ImmutableSet<TypeToken<? super T>> result = interfaces; 565 if (result == null) { 566 return (interfaces = FluentIterable.from(allTypes) 567 .filter(TypeFilter.INTERFACE_ONLY) 568 .toSet()); 569 } else { 570 return result; 571 } 572 } 573 574 @Override public TypeSet interfaces() { 575 return this; 576 } 577 578 @Override public Set<Class<? super T>> rawTypes() { 579 // Java has no way to express ? super T when we parameterize TypeToken vs. Class. 580 @SuppressWarnings({"unchecked", "rawtypes"}) 581 ImmutableList<Class<? super T>> collectedTypes = (ImmutableList) 582 TypeCollector.FOR_RAW_TYPE.collectTypes(getImmediateRawTypes()); 583 return FluentIterable.from(collectedTypes) 584 .filter(new Predicate<Class<?>>() { 585 @Override public boolean apply(Class<?> type) { 586 return type.isInterface(); 587 } 588 }) 589 .toSet(); 590 } 591 592 @Override public TypeSet classes() { 593 throw new UnsupportedOperationException("interfaces().classes() not supported."); 594 } 595 596 private Object readResolve() { 597 return getTypes().interfaces(); 598 } 599 600 private static final long serialVersionUID = 0; 601 } 602 603 private final class ClassSet extends TypeSet { 604 605 private transient ImmutableSet<TypeToken<? super T>> classes; 606 607 @Override protected Set<TypeToken<? super T>> delegate() { 608 ImmutableSet<TypeToken<? super T>> result = classes; 609 if (result == null) { 610 @SuppressWarnings({"unchecked", "rawtypes"}) 611 ImmutableList<TypeToken<? super T>> collectedTypes = (ImmutableList) 612 TypeCollector.FOR_GENERIC_TYPE.classesOnly().collectTypes(TypeToken.this); 613 return (classes = FluentIterable.from(collectedTypes) 614 .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD) 615 .toSet()); 616 } else { 617 return result; 618 } 619 } 620 621 @Override public TypeSet classes() { 622 return this; 623 } 624 625 @Override public Set<Class<? super T>> rawTypes() { 626 // Java has no way to express ? super T when we parameterize TypeToken vs. Class. 627 @SuppressWarnings({"unchecked", "rawtypes"}) 628 ImmutableList<Class<? super T>> collectedTypes = (ImmutableList) 629 TypeCollector.FOR_RAW_TYPE.classesOnly().collectTypes(getImmediateRawTypes()); 630 return ImmutableSet.copyOf(collectedTypes); 631 } 632 633 @Override public TypeSet interfaces() { 634 throw new UnsupportedOperationException("classes().interfaces() not supported."); 635 } 636 637 private Object readResolve() { 638 return getTypes().classes(); 639 } 640 641 private static final long serialVersionUID = 0; 642 } 643 644 private enum TypeFilter implements Predicate<TypeToken<?>> { 645 646 IGNORE_TYPE_VARIABLE_OR_WILDCARD { 647 @Override public boolean apply(TypeToken<?> type) { 648 return !(type.runtimeType instanceof TypeVariable 649 || type.runtimeType instanceof WildcardType); 650 } 651 }, 652 INTERFACE_ONLY { 653 @Override public boolean apply(TypeToken<?> type) { 654 return type.getRawType().isInterface(); 655 } 656 } 657 } 658 659 /** 660 * Returns true if {@code o} is another {@code TypeToken} that represents the same {@link Type}. 661 */ 662 @Override public boolean equals(@Nullable Object o) { 663 if (o instanceof TypeToken) { 664 TypeToken<?> that = (TypeToken<?>) o; 665 return runtimeType.equals(that.runtimeType); 666 } 667 return false; 668 } 669 670 @Override public int hashCode() { 671 return runtimeType.hashCode(); 672 } 673 674 @Override public String toString() { 675 return Types.toString(runtimeType); 676 } 677 678 /** Implemented to support serialization of subclasses. */ 679 protected Object writeReplace() { 680 // TypeResolver just transforms the type to our own impls that are Serializable 681 // except TypeVariable. 682 return of(new TypeResolver().resolveType(runtimeType)); 683 } 684 685 /** 686 * Ensures that this type token doesn't contain type variables, which can cause unchecked type 687 * errors for callers like {@link TypeToInstanceMap}. 688 */ 689 final TypeToken<T> rejectTypeVariables() { 690 checkArgument(!Types.containsTypeVariable(runtimeType), 691 "%s contains a type variable and is not safe for the operation"); 692 return this; 693 } 694 695 private static boolean isAssignable(Type from, Type to) { 696 if (to.equals(from)) { 697 return true; 698 } 699 if (to instanceof WildcardType) { 700 return isAssignableToWildcardType(from, (WildcardType) to); 701 } 702 // if "from" is type variable, it's assignable if any of its "extends" 703 // bounds is assignable to "to". 704 if (from instanceof TypeVariable) { 705 return isAssignableFromAny(((TypeVariable<?>) from).getBounds(), to); 706 } 707 // if "from" is wildcard, it'a assignable to "to" if any of its "extends" 708 // bounds is assignable to "to". 709 if (from instanceof WildcardType) { 710 return isAssignableFromAny(((WildcardType) from).getUpperBounds(), to); 711 } 712 if (from instanceof GenericArrayType) { 713 return isAssignableFromGenericArrayType((GenericArrayType) from, to); 714 } 715 // Proceed to regular Type assignability check 716 if (to instanceof Class) { 717 return isAssignableToClass(from, (Class<?>) to); 718 } else if (to instanceof ParameterizedType) { 719 return isAssignableToParameterizedType(from, (ParameterizedType) to); 720 } else if (to instanceof GenericArrayType) { 721 return isAssignableToGenericArrayType(from, (GenericArrayType) to); 722 } else { // to instanceof TypeVariable 723 return false; 724 } 725 } 726 727 private static boolean isAssignableFromAny(Type[] fromTypes, Type to) { 728 for (Type from : fromTypes) { 729 if (isAssignable(from, to)) { 730 return true; 731 } 732 } 733 return false; 734 } 735 736 private static boolean isAssignableToClass(Type from, Class<?> to) { 737 return to.isAssignableFrom(getRawType(from)); 738 } 739 740 private static boolean isAssignableToWildcardType( 741 Type from, WildcardType to) { 742 // if "to" is <? extends Foo>, "from" can be: 743 // Foo, SubFoo, <? extends Foo>, <? extends SubFoo>, <T extends Foo> or 744 // <T extends SubFoo>. 745 // if "to" is <? super Foo>, "from" can be: 746 // Foo, SuperFoo, <? super Foo> or <? super SuperFoo>. 747 return isAssignable(from, supertypeBound(to)) && isAssignableBySubtypeBound(from, to); 748 } 749 750 private static boolean isAssignableBySubtypeBound(Type from, WildcardType to) { 751 Type toSubtypeBound = subtypeBound(to); 752 if (toSubtypeBound == null) { 753 return true; 754 } 755 Type fromSubtypeBound = subtypeBound(from); 756 if (fromSubtypeBound == null) { 757 return false; 758 } 759 return isAssignable(toSubtypeBound, fromSubtypeBound); 760 } 761 762 private static boolean isAssignableToParameterizedType(Type from, ParameterizedType to) { 763 Class<?> matchedClass = getRawType(to); 764 if (!matchedClass.isAssignableFrom(getRawType(from))) { 765 return false; 766 } 767 Type[] typeParams = matchedClass.getTypeParameters(); 768 Type[] toTypeArgs = to.getActualTypeArguments(); 769 TypeToken<?> fromTypeToken = of(from); 770 for (int i = 0; i < typeParams.length; i++) { 771 // If "to" is "List<? extends CharSequence>" 772 // and "from" is StringArrayList, 773 // First step is to figure out StringArrayList "is-a" List<E> and <E> is 774 // String. 775 // typeParams[0] is E and fromTypeToken.get(typeParams[0]) will resolve to 776 // String. 777 // String is then matched against <? extends CharSequence>. 778 Type fromTypeArg = fromTypeToken.resolveType(typeParams[i]).runtimeType; 779 if (!matchTypeArgument(fromTypeArg, toTypeArgs[i])) { 780 return false; 781 } 782 } 783 return true; 784 } 785 786 private static boolean isAssignableToGenericArrayType(Type from, GenericArrayType to) { 787 if (from instanceof Class) { 788 Class<?> fromClass = (Class<?>) from; 789 if (!fromClass.isArray()) { 790 return false; 791 } 792 return isAssignable(fromClass.getComponentType(), to.getGenericComponentType()); 793 } else if (from instanceof GenericArrayType) { 794 GenericArrayType fromArrayType = (GenericArrayType) from; 795 return isAssignable(fromArrayType.getGenericComponentType(), to.getGenericComponentType()); 796 } else { 797 return false; 798 } 799 } 800 801 private static boolean isAssignableFromGenericArrayType(GenericArrayType from, Type to) { 802 if (to instanceof Class) { 803 Class<?> toClass = (Class<?>) to; 804 if (!toClass.isArray()) { 805 return toClass == Object.class; // any T[] is assignable to Object 806 } 807 return isAssignable(from.getGenericComponentType(), toClass.getComponentType()); 808 } else if (to instanceof GenericArrayType) { 809 GenericArrayType toArrayType = (GenericArrayType) to; 810 return isAssignable(from.getGenericComponentType(), toArrayType.getGenericComponentType()); 811 } else { 812 return false; 813 } 814 } 815 816 private static boolean matchTypeArgument(Type from, Type to) { 817 if (from.equals(to)) { 818 return true; 819 } 820 if (to instanceof WildcardType) { 821 return isAssignableToWildcardType(from, (WildcardType) to); 822 } 823 return false; 824 } 825 826 private static Type supertypeBound(Type type) { 827 if (type instanceof WildcardType) { 828 return supertypeBound((WildcardType) type); 829 } 830 return type; 831 } 832 833 private static Type supertypeBound(WildcardType type) { 834 Type[] upperBounds = type.getUpperBounds(); 835 if (upperBounds.length == 1) { 836 return supertypeBound(upperBounds[0]); 837 } else if (upperBounds.length == 0) { 838 return Object.class; 839 } else { 840 throw new AssertionError( 841 "There should be at most one upper bound for wildcard type: " + type); 842 } 843 } 844 845 @Nullable private static Type subtypeBound(Type type) { 846 if (type instanceof WildcardType) { 847 return subtypeBound((WildcardType) type); 848 } else { 849 return type; 850 } 851 } 852 853 @Nullable private static Type subtypeBound(WildcardType type) { 854 Type[] lowerBounds = type.getLowerBounds(); 855 if (lowerBounds.length == 1) { 856 return subtypeBound(lowerBounds[0]); 857 } else if (lowerBounds.length == 0) { 858 return null; 859 } else { 860 throw new AssertionError( 861 "Wildcard should have at most one lower bound: " + type); 862 } 863 } 864 865 @VisibleForTesting static Class<?> getRawType(Type type) { 866 // For wildcard or type variable, the first bound determines the runtime type. 867 return getRawTypes(type).iterator().next(); 868 } 869 870 @VisibleForTesting static ImmutableSet<Class<?>> getRawTypes(Type type) { 871 if (type instanceof Class) { 872 return ImmutableSet.<Class<?>>of((Class<?>) type); 873 } else if (type instanceof ParameterizedType) { 874 ParameterizedType parameterizedType = (ParameterizedType) type; 875 // JDK implementation declares getRawType() to return Class<?>: http://goo.gl/YzaEd 876 return ImmutableSet.<Class<?>>of((Class<?>) parameterizedType.getRawType()); 877 } else if (type instanceof GenericArrayType) { 878 GenericArrayType genericArrayType = (GenericArrayType) type; 879 return ImmutableSet.<Class<?>>of(Types.getArrayClass( 880 getRawType(genericArrayType.getGenericComponentType()))); 881 } else if (type instanceof TypeVariable) { 882 return getRawTypes(((TypeVariable<?>) type).getBounds()); 883 } else if (type instanceof WildcardType) { 884 return getRawTypes(((WildcardType) type).getUpperBounds()); 885 } else { 886 throw new AssertionError(type + " unsupported"); 887 } 888 } 889 890 private static ImmutableSet<Class<?>> getRawTypes(Type[] types) { 891 ImmutableSet.Builder<Class<?>> builder = ImmutableSet.builder(); 892 for (Type type : types) { 893 builder.addAll(getRawTypes(type)); 894 } 895 return builder.build(); 896 } 897 898 /** 899 * Returns the type token representing the generic type declaration of {@code cls}. For example: 900 * {@code TypeToken.getGenericType(Iterable.class)} returns {@code Iterable<T>}. 901 * 902 * <p>If {@code cls} isn't parameterized and isn't a generic array, the type token of the class is 903 * returned. 904 */ 905 @VisibleForTesting static <T> TypeToken<? extends T> toGenericType(Class<T> cls) { 906 if (cls.isArray()) { 907 Type arrayOfGenericType = Types.newArrayType( 908 // If we are passed with int[].class, don't turn it to GenericArrayType 909 toGenericType(cls.getComponentType()).runtimeType); 910 @SuppressWarnings("unchecked") // array is covariant 911 TypeToken<? extends T> result = (TypeToken<? extends T>) of(arrayOfGenericType); 912 return result; 913 } 914 TypeVariable<Class<T>>[] typeParams = cls.getTypeParameters(); 915 if (typeParams.length > 0) { 916 @SuppressWarnings("unchecked") // Like, it's Iterable<T> for Iterable.class 917 TypeToken<? extends T> type = (TypeToken<? extends T>) 918 of(Types.newParameterizedType(cls, typeParams)); 919 return type; 920 } else { 921 return of(cls); 922 } 923 } 924 925 private TypeToken<? super T> getSupertypeFromUpperBounds( 926 Class<? super T> supertype, Type[] upperBounds) { 927 for (Type upperBound : upperBounds) { 928 @SuppressWarnings("unchecked") // T's upperbound is <? super T>. 929 TypeToken<? super T> bound = (TypeToken<? super T>) of(upperBound); 930 if (of(supertype).isAssignableFrom(bound)) { 931 @SuppressWarnings({"rawtypes", "unchecked"}) // guarded by the isAssignableFrom check. 932 TypeToken<? super T> result = bound.getSupertype((Class) supertype); 933 return result; 934 } 935 } 936 throw new IllegalArgumentException(supertype + " isn't a super type of " + this); 937 } 938 939 private TypeToken<? extends T> getSubtypeFromLowerBounds(Class<?> subclass, Type[] lowerBounds) { 940 for (Type lowerBound : lowerBounds) { 941 @SuppressWarnings("unchecked") // T's lower bound is <? extends T> 942 TypeToken<? extends T> bound = (TypeToken<? extends T>) of(lowerBound); 943 // Java supports only one lowerbound anyway. 944 return bound.getSubtype(subclass); 945 } 946 throw new IllegalArgumentException(subclass + " isn't a subclass of " + this); 947 } 948 949 private TypeToken<? super T> getArraySupertype(Class<? super T> supertype) { 950 // with component type, we have lost generic type information 951 // Use raw type so that compiler allows us to call getSupertype() 952 @SuppressWarnings("rawtypes") 953 TypeToken componentType = checkNotNull(getComponentType(), 954 "%s isn't a super type of %s", supertype, this); 955 // array is covariant. component type is super type, so is the array type. 956 @SuppressWarnings("unchecked") // going from raw type back to generics 957 TypeToken<?> componentSupertype = componentType.getSupertype(supertype.getComponentType()); 958 @SuppressWarnings("unchecked") // component type is super type, so is array type. 959 TypeToken<? super T> result = (TypeToken<? super T>) 960 // If we are passed with int[].class, don't turn it to GenericArrayType 961 of(newArrayClassOrGenericArrayType(componentSupertype.runtimeType)); 962 return result; 963 } 964 965 private TypeToken<? extends T> getArraySubtype(Class<?> subclass) { 966 // array is covariant. component type is subtype, so is the array type. 967 TypeToken<?> componentSubtype = getComponentType() 968 .getSubtype(subclass.getComponentType()); 969 @SuppressWarnings("unchecked") // component type is subtype, so is array type. 970 TypeToken<? extends T> result = (TypeToken<? extends T>) 971 // If we are passed with int[].class, don't turn it to GenericArrayType 972 of(newArrayClassOrGenericArrayType(componentSubtype.runtimeType)); 973 return result; 974 } 975 976 private Type resolveTypeArgsForSubclass(Class<?> subclass) { 977 if (runtimeType instanceof Class) { 978 // no resolution needed 979 return subclass; 980 } 981 // class Base<A, B> {} 982 // class Sub<X, Y> extends Base<X, Y> {} 983 // Base<String, Integer>.subtype(Sub.class): 984 985 // Sub<X, Y>.getSupertype(Base.class) => Base<X, Y> 986 // => X=String, Y=Integer 987 // => Sub<X, Y>=Sub<String, Integer> 988 TypeToken<?> genericSubtype = toGenericType(subclass); 989 @SuppressWarnings({"rawtypes", "unchecked"}) // subclass isn't <? extends T> 990 Type supertypeWithArgsFromSubtype = genericSubtype 991 .getSupertype((Class) getRawType()) 992 .runtimeType; 993 return new TypeResolver().where(supertypeWithArgsFromSubtype, runtimeType) 994 .resolveType(genericSubtype.runtimeType); 995 } 996 997 /** 998 * Creates an array class if {@code componentType} is a class, or else, a 999 * {@link GenericArrayType}. This is what Java7 does for generic array type 1000 * parameters. 1001 */ 1002 private static Type newArrayClassOrGenericArrayType(Type componentType) { 1003 return Types.JavaVersion.JAVA7.newArrayType(componentType); 1004 } 1005 1006 private static final class SimpleTypeToken<T> extends TypeToken<T> { 1007 1008 SimpleTypeToken(Type type) { 1009 super(type); 1010 } 1011 1012 private static final long serialVersionUID = 0; 1013 } 1014 1015 /** 1016 * Collects parent types from a sub type. 1017 * 1018 * @param <K> The type "kind". Either a TypeToken, or Class. 1019 */ 1020 private abstract static class TypeCollector<K> { 1021 1022 static final TypeCollector<TypeToken<?>> FOR_GENERIC_TYPE = 1023 new TypeCollector<TypeToken<?>>() { 1024 @Override Class<?> getRawType(TypeToken<?> type) { 1025 return type.getRawType(); 1026 } 1027 1028 @Override Iterable<? extends TypeToken<?>> getInterfaces(TypeToken<?> type) { 1029 return type.getGenericInterfaces(); 1030 } 1031 1032 @Nullable 1033 @Override TypeToken<?> getSuperclass(TypeToken<?> type) { 1034 return type.getGenericSuperclass(); 1035 } 1036 }; 1037 1038 static final TypeCollector<Class<?>> FOR_RAW_TYPE = 1039 new TypeCollector<Class<?>>() { 1040 @Override Class<?> getRawType(Class<?> type) { 1041 return type; 1042 } 1043 1044 @Override Iterable<? extends Class<?>> getInterfaces(Class<?> type) { 1045 return Arrays.asList(type.getInterfaces()); 1046 } 1047 1048 @Nullable 1049 @Override Class<?> getSuperclass(Class<?> type) { 1050 return type.getSuperclass(); 1051 } 1052 }; 1053 1054 /** For just classes, we don't have to traverse interfaces. */ 1055 final TypeCollector<K> classesOnly() { 1056 return new ForwardingTypeCollector<K>(this) { 1057 @Override Iterable<? extends K> getInterfaces(K type) { 1058 return ImmutableSet.of(); 1059 } 1060 @Override ImmutableList<K> collectTypes(Iterable<? extends K> types) { 1061 ImmutableList.Builder<K> builder = ImmutableList.builder(); 1062 for (K type : types) { 1063 if (!getRawType(type).isInterface()) { 1064 builder.add(type); 1065 } 1066 } 1067 return super.collectTypes(builder.build()); 1068 } 1069 }; 1070 } 1071 1072 final ImmutableList<K> collectTypes(K type) { 1073 return collectTypes(ImmutableList.of(type)); 1074 } 1075 1076 ImmutableList<K> collectTypes(Iterable<? extends K> types) { 1077 // type -> order number. 1 for Object, 2 for anything directly below, so on so forth. 1078 Map<K, Integer> map = Maps.newHashMap(); 1079 for (K type : types) { 1080 collectTypes(type, map); 1081 } 1082 return sortKeysByValue(map, Ordering.natural().reverse()); 1083 } 1084 1085 /** Collects all types to map, and returns the total depth from T up to Object. */ 1086 private int collectTypes(K type, Map<? super K, Integer> map) { 1087 Integer existing = map.get(this); 1088 if (existing != null) { 1089 // short circuit: if set contains type it already contains its supertypes 1090 return existing; 1091 } 1092 int aboveMe = getRawType(type).isInterface() 1093 ? 1 // interfaces should be listed before Object 1094 : 0; 1095 for (K interfaceType : getInterfaces(type)) { 1096 aboveMe = Math.max(aboveMe, collectTypes(interfaceType, map)); 1097 } 1098 K superclass = getSuperclass(type); 1099 if (superclass != null) { 1100 aboveMe = Math.max(aboveMe, collectTypes(superclass, map)); 1101 } 1102 /* 1103 * TODO(benyu): should we include Object for interface? 1104 * Also, CharSequence[] and Object[] for String[]? 1105 * 1106 */ 1107 map.put(type, aboveMe + 1); 1108 return aboveMe + 1; 1109 } 1110 1111 private static <K, V> ImmutableList<K> sortKeysByValue( 1112 final Map<K, V> map, final Comparator<? super V> valueComparator) { 1113 Ordering<K> keyOrdering = new Ordering<K>() { 1114 @Override public int compare(K left, K right) { 1115 return valueComparator.compare(map.get(left), map.get(right)); 1116 } 1117 }; 1118 return keyOrdering.immutableSortedCopy(map.keySet()); 1119 } 1120 1121 abstract Class<?> getRawType(K type); 1122 abstract Iterable<? extends K> getInterfaces(K type); 1123 @Nullable abstract K getSuperclass(K type); 1124 1125 private static class ForwardingTypeCollector<K> extends TypeCollector<K> { 1126 1127 private final TypeCollector<K> delegate; 1128 1129 ForwardingTypeCollector(TypeCollector<K> delegate) { 1130 this.delegate = delegate; 1131 } 1132 1133 @Override Class<?> getRawType(K type) { 1134 return delegate.getRawType(type); 1135 } 1136 1137 @Override Iterable<? extends K> getInterfaces(K type) { 1138 return delegate.getInterfaces(type); 1139 } 1140 1141 @Override K getSuperclass(K type) { 1142 return delegate.getSuperclass(type); 1143 } 1144 } 1145 } 1146}