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