/*
* Copyright (C) 2006 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jersey.repackaged.com.google.common.reflect;
import static jersey.repackaged.com.google.common.base.Preconditions.checkArgument;
import static jersey.repackaged.com.google.common.base.Preconditions.checkNotNull;
import static jersey.repackaged.com.google.common.base.Preconditions.checkState;
import jersey.repackaged.com.google.common.annotations.Beta;
import jersey.repackaged.com.google.common.annotations.VisibleForTesting;
import jersey.repackaged.com.google.common.base.Predicate;
import jersey.repackaged.com.google.common.collect.FluentIterable;
import jersey.repackaged.com.google.common.collect.ForwardingSet;
import jersey.repackaged.com.google.common.collect.ImmutableList;
import jersey.repackaged.com.google.common.collect.ImmutableMap;
import jersey.repackaged.com.google.common.collect.ImmutableSet;
import jersey.repackaged.com.google.common.collect.Maps;
import jersey.repackaged.com.google.common.collect.Ordering;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* A {@link Type} with generics.
*
* Operations that are otherwise only available in {@link Class} are implemented to support
* {@code Type}, for example {@link #isAssignableFrom}, {@link #isArray} and {@link
* #getComponentType}. It also provides additional utilities such as {@link #getTypes} and {@link
* #resolveType} etc.
*
*
There are three ways to get a {@code TypeToken} instance:
*
* {@code TypeToken} is serializable when no type variable is contained in the type.
*
*
Note to Guice users: {@code} TypeToken is similar to Guice's {@code TypeLiteral} class,
* but with one important difference: it supports non-reified types such as {@code T},
* {@code List} or even {@code List}; while TypeLiteral does not.
* TypeToken is also serializable and offers numerous additional utility methods.
*
* @author Bob Lee
* @author Sven Mawson
* @author Ben Yu
* @since 12.0
*/
@Beta
@SuppressWarnings("serial") // SimpleTypeToken is the serialized form.
public abstract class TypeToken extends TypeCapture implements Serializable {
private final Type runtimeType;
/** Resolver for resolving types with {@link #runtimeType} as context. */
private transient TypeResolver typeResolver;
/**
* Constructs a new type token of {@code T}.
*
* Clients create an empty anonymous subclass. Doing so embeds the type
* parameter in the anonymous class's type hierarchy so we can reconstitute
* it at runtime despite erasure.
*
*
For example:
{@code
*
* TypeToken> t = new TypeToken>() {};
* }
*/
protected TypeToken() {
this.runtimeType = capture();
checkState(!(runtimeType instanceof TypeVariable),
"Cannot construct a TypeToken for a type variable.\n" +
"You probably meant to call new TypeToken<%s>(getClass()) " +
"that can resolve the type variable for you.\n" +
"If you do need to create a TypeToken of a type variable, " +
"please use TypeToken.of() instead.", runtimeType);
}
/**
* Constructs a new type token of {@code T} while resolving free type variables in the context of
* {@code declaringClass}.
*
* Clients create an empty anonymous subclass. Doing so embeds the type
* parameter in the anonymous class's type hierarchy so we can reconstitute
* it at runtime despite erasure.
*
*
For example:
{@code
*
* abstract class IKnowMyType {
* TypeToken getMyType() {
* return new TypeToken(getClass()) {};
* }
* }
*
* new IKnowMyType() {}.getMyType() => String
* }
*/
protected TypeToken(Class declaringClass) {
Type captured = super.capture();
if (captured instanceof Class) {
this.runtimeType = captured;
} else {
this.runtimeType = of(declaringClass).resolveType(captured).runtimeType;
}
}
private TypeToken(Type type) {
this.runtimeType = checkNotNull(type);
}
/** Returns an instance of type token that wraps {@code type}. */
public static TypeToken of(Class type) {
return new SimpleTypeToken(type);
}
/** Returns an instance of type token that wraps {@code type}. */
public static TypeToken of(Type type) {
return new SimpleTypeToken(type);
}
/**
* Returns the raw type of {@code T}. Formally speaking, if {@code T} is returned by
* {@link java.lang.reflect.Method#getGenericReturnType}, the raw type is what's returned by
* {@link java.lang.reflect.Method#getReturnType} of the same method object. Specifically:
*
* If {@code T} is a {@code Class} itself, {@code T} itself is returned.
* If {@code T} is a {@link ParameterizedType}, the raw type of the parameterized type is
* returned.
* If {@code T} is a {@link GenericArrayType}, the returned type is the corresponding array
* class. For example: {@code List[] => List[]}.
* If {@code T} is a type variable or a wildcard type, the raw type of the first upper bound
* is returned. For example: {@code => Foo}.
*
*/
public final Class getRawType() {
Class rawType = getRawType(runtimeType);
@SuppressWarnings("unchecked") // raw type is |T|
Class result = (Class) rawType;
return result;
}
/**
* Returns the raw type of the class or parameterized type; if {@code T} is type variable or
* wildcard type, the raw types of all its upper bounds are returned.
*/
private ImmutableSet> getImmediateRawTypes() {
// Cast from ImmutableSet> to ImmutableSet>
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableSet> result = (ImmutableSet) getRawTypes(runtimeType);
return result;
}
/** Returns the represented type. */
public final Type getType() {
return runtimeType;
}
/**
* Returns a new {@code TypeToken} where type variables represented by {@code typeParam}
* are substituted by {@code typeArg}. For example, it can be used to construct
* {@code Map} for any {@code K} and {@code V} type: {@code
*
* static TypeToken> mapOf(
* TypeToken keyType, TypeToken valueType) {
* return new TypeToken>() {}
* .where(new TypeParameter() {}, keyType)
* .where(new TypeParameter() {}, valueType);
* }
* }
*
* @param The parameter type
* @param typeParam the parameter type variable
* @param typeArg the actual type to substitute
*/
public final TypeToken where(TypeParameter typeParam, TypeToken typeArg) {
TypeResolver resolver = new TypeResolver()
.where(ImmutableMap.of(typeParam.typeVariable, typeArg.runtimeType));
// If there's any type error, we'd report now rather than later.
return new SimpleTypeToken(resolver.resolveType(runtimeType));
}
/**
* Returns a new {@code TypeToken} where type variables represented by {@code typeParam}
* are substituted by {@code typeArg}. For example, it can be used to construct
* {@code Map} for any {@code K} and {@code V} type: {@code
*
* static TypeToken> mapOf(
* Class keyType, Class valueType) {
* return new TypeToken>() {}
* .where(new TypeParameter() {}, keyType)
* .where(new TypeParameter() {}, valueType);
* }
* }
*
* @param The parameter type
* @param typeParam the parameter type variable
* @param typeArg the actual type to substitute
*/
public final TypeToken where(TypeParameter typeParam, Class typeArg) {
return where(typeParam, of(typeArg));
}
/**
* Resolves the given {@code type} against the type context represented by this type.
* For example: {@code
*
* new TypeToken>() {}.resolveType(
* List.class.getMethod("get", int.class).getGenericReturnType())
* => String.class
* }
*/
public final TypeToken resolveType(Type type) {
checkNotNull(type);
TypeResolver resolver = typeResolver;
if (resolver == null) {
resolver = (typeResolver = TypeResolver.accordingTo(runtimeType));
}
return of(resolver.resolveType(type));
}
private Type[] resolveInPlace(Type[] types) {
for (int i = 0; i < types.length; i++) {
types[i] = resolveType(types[i]).getType();
}
return types;
}
private TypeToken resolveSupertype(Type type) {
TypeToken supertype = resolveType(type);
// super types' type mapping is a subset of type mapping of this type.
supertype.typeResolver = typeResolver;
return supertype;
}
/**
* Returns the generic superclass of this type or {@code null} if the type represents
* {@link Object} or an interface. This method is similar but different from {@link
* Class#getGenericSuperclass}. For example, {@code
* new TypeToken() {}.getGenericSuperclass()} will return {@code
* new TypeToken>() {}}; while {@code
* StringArrayList.class.getGenericSuperclass()} will return {@code ArrayList}, where {@code E}
* is the type variable declared by class {@code ArrayList}.
*
* If this type is a type variable or wildcard, its first upper bound is examined and returned
* if the bound is a class or extends from a class. This means that the returned type could be a
* type variable too.
*/
@Nullable
final TypeToken getGenericSuperclass() {
if (runtimeType instanceof TypeVariable) {
// First bound is always the super class, if one exists.
return boundAsSuperclass(((TypeVariable) runtimeType).getBounds()[0]);
}
if (runtimeType instanceof WildcardType) {
// wildcard has one and only one upper bound.
return boundAsSuperclass(((WildcardType) runtimeType).getUpperBounds()[0]);
}
Type superclass = getRawType().getGenericSuperclass();
if (superclass == null) {
return null;
}
@SuppressWarnings("unchecked") // super class of T
TypeToken superToken = (TypeToken) resolveSupertype(superclass);
return superToken;
}
@Nullable private TypeToken boundAsSuperclass(Type bound) {
TypeToken token = of(bound);
if (token.getRawType().isInterface()) {
return null;
}
@SuppressWarnings("unchecked") // only upper bound of T is passed in.
TypeToken superclass = (TypeToken) token;
return superclass;
}
/**
* Returns the generic interfaces that this type directly {@code implements}. This method is
* similar but different from {@link Class#getGenericInterfaces()}. For example, {@code
* new TypeToken>() {}.getGenericInterfaces()} will return a list that contains
* {@code new TypeToken>() {}}; while {@code List.class.getGenericInterfaces()}
* will return an array that contains {@code Iterable}, where the {@code T} is the type
* variable declared by interface {@code Iterable}.
*
* If this type is a type variable or wildcard, its upper bounds are examined and those that
* are either an interface or upper-bounded only by interfaces are returned. This means that the
* returned types could include type variables too.
*/
final ImmutableList> getGenericInterfaces() {
if (runtimeType instanceof TypeVariable) {
return boundsAsInterfaces(((TypeVariable) runtimeType).getBounds());
}
if (runtimeType instanceof WildcardType) {
return boundsAsInterfaces(((WildcardType) runtimeType).getUpperBounds());
}
ImmutableList.Builder> builder = ImmutableList.builder();
for (Type interfaceType : getRawType().getGenericInterfaces()) {
@SuppressWarnings("unchecked") // interface of T
TypeToken resolvedInterface = (TypeToken)
resolveSupertype(interfaceType);
builder.add(resolvedInterface);
}
return builder.build();
}
private ImmutableList> boundsAsInterfaces(Type[] bounds) {
ImmutableList.Builder> builder = ImmutableList.builder();
for (Type bound : bounds) {
@SuppressWarnings("unchecked") // upper bound of T
TypeToken boundType = (TypeToken) of(bound);
if (boundType.getRawType().isInterface()) {
builder.add(boundType);
}
}
return builder.build();
}
/**
* Returns the set of interfaces and classes that this type is or is a subtype of. The returned
* types are parameterized with proper type arguments.
*
* Subtypes are always listed before supertypes. But the reverse is not true. A type isn't
* necessarily a subtype of all the types following. Order between types without subtype
* relationship is arbitrary and not guaranteed.
*
*
If this type is a type variable or wildcard, upper bounds that are themselves type variables
* aren't included (their super interfaces and superclasses are).
*/
public final TypeSet getTypes() {
return new TypeSet();
}
/**
* Returns the generic form of {@code superclass}. For example, if this is
* {@code ArrayList}, {@code Iterable} is returned given the
* input {@code Iterable.class}.
*/
public final TypeToken getSupertype(Class superclass) {
checkArgument(superclass.isAssignableFrom(getRawType()),
"%s is not a super class of %s", superclass, this);
if (runtimeType instanceof TypeVariable) {
return getSupertypeFromUpperBounds(superclass, ((TypeVariable) runtimeType).getBounds());
}
if (runtimeType instanceof WildcardType) {
return getSupertypeFromUpperBounds(superclass, ((WildcardType) runtimeType).getUpperBounds());
}
if (superclass.isArray()) {
return getArraySupertype(superclass);
}
@SuppressWarnings("unchecked") // resolved supertype
TypeToken supertype = (TypeToken)
resolveSupertype(toGenericType(superclass).runtimeType);
return supertype;
}
/**
* Returns subtype of {@code this} with {@code subclass} as the raw class.
* For example, if this is {@code Iterable} and {@code subclass} is {@code List},
* {@code List} is returned.
*/
public final TypeToken getSubtype(Class subclass) {
checkArgument(!(runtimeType instanceof TypeVariable),
"Cannot get subtype of type variable <%s>", this);
if (runtimeType instanceof WildcardType) {
return getSubtypeFromLowerBounds(subclass, ((WildcardType) runtimeType).getLowerBounds());
}
checkArgument(getRawType().isAssignableFrom(subclass),
"%s isn't a subclass of %s", subclass, this);
// unwrap array type if necessary
if (isArray()) {
return getArraySubtype(subclass);
}
@SuppressWarnings("unchecked") // guarded by the isAssignableFrom() statement above
TypeToken subtype = (TypeToken)
of(resolveTypeArgsForSubclass(subclass));
return subtype;
}
/** Returns true if this type is assignable from the given {@code type}. */
public final boolean isAssignableFrom(TypeToken type) {
return isAssignableFrom(type.runtimeType);
}
/** Check if this type is assignable from the given {@code type}. */
public final boolean isAssignableFrom(Type type) {
return isAssignable(checkNotNull(type), runtimeType);
}
/**
* Returns true if this type is known to be an array type, such as {@code int[]}, {@code T[]},
* {@code []>} etc.
*/
public final boolean isArray() {
return getComponentType() != null;
}
/**
* Returns the array component type if this type represents an array ({@code int[]}, {@code T[]},
* {@code []>} etc.), or else {@code null} is returned.
*/
@Nullable public final TypeToken getComponentType() {
Type componentType = Types.getComponentType(runtimeType);
if (componentType == null) {
return null;
}
return of(componentType);
}
/**
* Returns the {@link Invokable} for {@code method}, which must be a member of {@code T}.
*
* @since 14.0
*/
public final Invokable method(Method method) {
checkArgument(of(method.getDeclaringClass()).isAssignableFrom(this),
"%s not declared by %s", method, this);
return new Invokable.MethodInvokable(method) {
@Override Type getGenericReturnType() {
return resolveType(super.getGenericReturnType()).getType();
}
@Override Type[] getGenericParameterTypes() {
return resolveInPlace(super.getGenericParameterTypes());
}
@Override Type[] getGenericExceptionTypes() {
return resolveInPlace(super.getGenericExceptionTypes());
}
@Override public TypeToken getOwnerType() {
return TypeToken.this;
}
};
}
/**
* Returns the {@link Invokable} for {@code constructor}, which must be a member of {@code T}.
*
* @since 14.0
*/
public final Invokable constructor(Constructor constructor) {
checkArgument(constructor.getDeclaringClass() == getRawType(),
"%s not declared by %s", constructor, getRawType());
return new Invokable.ConstructorInvokable(constructor) {
@Override Type getGenericReturnType() {
return resolveType(super.getGenericReturnType()).getType();
}
@Override Type[] getGenericParameterTypes() {
return resolveInPlace(super.getGenericParameterTypes());
}
@Override Type[] getGenericExceptionTypes() {
return resolveInPlace(super.getGenericExceptionTypes());
}
@Override public TypeToken getOwnerType() {
return TypeToken.this;
}
};
}
/**
* The set of interfaces and classes that {@code T} is or is a subtype of. {@link Object} is not
* included in the set if this type is an interface.
*/
public class TypeSet extends ForwardingSet> implements Serializable {
private transient ImmutableSet> types;
TypeSet() {}
/** Returns the types that are interfaces implemented by this type. */
public TypeSet interfaces() {
return new InterfaceSet(this);
}
/** Returns the types that are classes. */
public TypeSet classes() {
return new ClassSet();
}
@Override protected Set> delegate() {
ImmutableSet> filteredTypes = types;
if (filteredTypes == null) {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList> collectedTypes = (ImmutableList)
TypeCollector.FOR_GENERIC_TYPE.collectTypes(TypeToken.this);
return (types = FluentIterable.from(collectedTypes)
.filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
.toSet());
} else {
return filteredTypes;
}
}
/** Returns the raw types of the types in this set, in the same order. */
public Set> rawTypes() {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList> collectedTypes = (ImmutableList)
TypeCollector.FOR_RAW_TYPE.collectTypes(getImmediateRawTypes());
return ImmutableSet.copyOf(collectedTypes);
}
private static final long serialVersionUID = 0;
}
private final class InterfaceSet extends TypeSet {
private transient final TypeSet allTypes;
private transient ImmutableSet> interfaces;
InterfaceSet(TypeSet allTypes) {
this.allTypes = allTypes;
}
@Override protected Set> delegate() {
ImmutableSet> result = interfaces;
if (result == null) {
return (interfaces = FluentIterable.from(allTypes)
.filter(TypeFilter.INTERFACE_ONLY)
.toSet());
} else {
return result;
}
}
@Override public TypeSet interfaces() {
return this;
}
@Override public Set> rawTypes() {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList> collectedTypes = (ImmutableList)
TypeCollector.FOR_RAW_TYPE.collectTypes(getImmediateRawTypes());
return FluentIterable.from(collectedTypes)
.filter(new Predicate>() {
@Override public boolean apply(Class type) {
return type.isInterface();
}
})
.toSet();
}
@Override public TypeSet classes() {
throw new UnsupportedOperationException("interfaces().classes() not supported.");
}
private Object readResolve() {
return getTypes().interfaces();
}
private static final long serialVersionUID = 0;
}
private final class ClassSet extends TypeSet {
private transient ImmutableSet> classes;
@Override protected Set> delegate() {
ImmutableSet> result = classes;
if (result == null) {
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList> collectedTypes = (ImmutableList)
TypeCollector.FOR_GENERIC_TYPE.classesOnly().collectTypes(TypeToken.this);
return (classes = FluentIterable.from(collectedTypes)
.filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD)
.toSet());
} else {
return result;
}
}
@Override public TypeSet classes() {
return this;
}
@Override public Set> rawTypes() {
// Java has no way to express ? super T when we parameterize TypeToken vs. Class.
@SuppressWarnings({"unchecked", "rawtypes"})
ImmutableList> collectedTypes = (ImmutableList)
TypeCollector.FOR_RAW_TYPE.classesOnly().collectTypes(getImmediateRawTypes());
return ImmutableSet.copyOf(collectedTypes);
}
@Override public TypeSet interfaces() {
throw new UnsupportedOperationException("classes().interfaces() not supported.");
}
private Object readResolve() {
return getTypes().classes();
}
private static final long serialVersionUID = 0;
}
private enum TypeFilter implements Predicate> {
IGNORE_TYPE_VARIABLE_OR_WILDCARD {
@Override public boolean apply(TypeToken type) {
return !(type.runtimeType instanceof TypeVariable
|| type.runtimeType instanceof WildcardType);
}
},
INTERFACE_ONLY {
@Override public boolean apply(TypeToken type) {
return type.getRawType().isInterface();
}
}
}
/**
* Returns true if {@code o} is another {@code TypeToken} that represents the same {@link Type}.
*/
@Override public boolean equals(@Nullable Object o) {
if (o instanceof TypeToken) {
TypeToken that = (TypeToken) o;
return runtimeType.equals(that.runtimeType);
}
return false;
}
@Override public int hashCode() {
return runtimeType.hashCode();
}
@Override public String toString() {
return Types.toString(runtimeType);
}
/** Implemented to support serialization of subclasses. */
protected Object writeReplace() {
// TypeResolver just transforms the type to our own impls that are Serializable
// except TypeVariable.
return of(new TypeResolver().resolveType(runtimeType));
}
/**
* Ensures that this type token doesn't contain type variables, which can cause unchecked type
* errors for callers like {@link TypeToInstanceMap}.
*/
final TypeToken rejectTypeVariables() {
checkArgument(!Types.containsTypeVariable(runtimeType),
"%s contains a type variable and is not safe for the operation");
return this;
}
private static boolean isAssignable(Type from, Type to) {
if (to.equals(from)) {
return true;
}
if (to instanceof WildcardType) {
return isAssignableToWildcardType(from, (WildcardType) to);
}
// if "from" is type variable, it's assignable if any of its "extends"
// bounds is assignable to "to".
if (from instanceof TypeVariable) {
return isAssignableFromAny(((TypeVariable) from).getBounds(), to);
}
// if "from" is wildcard, it'a assignable to "to" if any of its "extends"
// bounds is assignable to "to".
if (from instanceof WildcardType) {
return isAssignableFromAny(((WildcardType) from).getUpperBounds(), to);
}
if (from instanceof GenericArrayType) {
return isAssignableFromGenericArrayType((GenericArrayType) from, to);
}
// Proceed to regular Type assignability check
if (to instanceof Class) {
return isAssignableToClass(from, (Class) to);
} else if (to instanceof ParameterizedType) {
return isAssignableToParameterizedType(from, (ParameterizedType) to);
} else if (to instanceof GenericArrayType) {
return isAssignableToGenericArrayType(from, (GenericArrayType) to);
} else { // to instanceof TypeVariable
return false;
}
}
private static boolean isAssignableFromAny(Type[] fromTypes, Type to) {
for (Type from : fromTypes) {
if (isAssignable(from, to)) {
return true;
}
}
return false;
}
private static boolean isAssignableToClass(Type from, Class to) {
return to.isAssignableFrom(getRawType(from));
}
private static boolean isAssignableToWildcardType(
Type from, WildcardType to) {
// if "to" is , "from" can be:
// Foo, SubFoo, , , or
// .
// if "to" is , "from" can be:
// Foo, SuperFoo, or .
return isAssignable(from, supertypeBound(to)) && isAssignableBySubtypeBound(from, to);
}
private static boolean isAssignableBySubtypeBound(Type from, WildcardType to) {
Type toSubtypeBound = subtypeBound(to);
if (toSubtypeBound == null) {
return true;
}
Type fromSubtypeBound = subtypeBound(from);
if (fromSubtypeBound == null) {
return false;
}
return isAssignable(toSubtypeBound, fromSubtypeBound);
}
private static boolean isAssignableToParameterizedType(Type from, ParameterizedType to) {
Class matchedClass = getRawType(to);
if (!matchedClass.isAssignableFrom(getRawType(from))) {
return false;
}
Type[] typeParams = matchedClass.getTypeParameters();
Type[] toTypeArgs = to.getActualTypeArguments();
TypeToken fromTypeToken = of(from);
for (int i = 0; i < typeParams.length; i++) {
// If "to" is "List"
// and "from" is StringArrayList,
// First step is to figure out StringArrayList "is-a" List and is
// String.
// typeParams[0] is E and fromTypeToken.get(typeParams[0]) will resolve to
// String.
// String is then matched against .
Type fromTypeArg = fromTypeToken.resolveType(typeParams[i]).runtimeType;
if (!matchTypeArgument(fromTypeArg, toTypeArgs[i])) {
return false;
}
}
return true;
}
private static boolean isAssignableToGenericArrayType(Type from, GenericArrayType to) {
if (from instanceof Class) {
Class fromClass = (Class) from;
if (!fromClass.isArray()) {
return false;
}
return isAssignable(fromClass.getComponentType(), to.getGenericComponentType());
} else if (from instanceof GenericArrayType) {
GenericArrayType fromArrayType = (GenericArrayType) from;
return isAssignable(fromArrayType.getGenericComponentType(), to.getGenericComponentType());
} else {
return false;
}
}
private static boolean isAssignableFromGenericArrayType(GenericArrayType from, Type to) {
if (to instanceof Class) {
Class toClass = (Class) to;
if (!toClass.isArray()) {
return toClass == Object.class; // any T[] is assignable to Object
}
return isAssignable(from.getGenericComponentType(), toClass.getComponentType());
} else if (to instanceof GenericArrayType) {
GenericArrayType toArrayType = (GenericArrayType) to;
return isAssignable(from.getGenericComponentType(), toArrayType.getGenericComponentType());
} else {
return false;
}
}
private static boolean matchTypeArgument(Type from, Type to) {
if (from.equals(to)) {
return true;
}
if (to instanceof WildcardType) {
return isAssignableToWildcardType(from, (WildcardType) to);
}
return false;
}
private static Type supertypeBound(Type type) {
if (type instanceof WildcardType) {
return supertypeBound((WildcardType) type);
}
return type;
}
private static Type supertypeBound(WildcardType type) {
Type[] upperBounds = type.getUpperBounds();
if (upperBounds.length == 1) {
return supertypeBound(upperBounds[0]);
} else if (upperBounds.length == 0) {
return Object.class;
} else {
throw new AssertionError(
"There should be at most one upper bound for wildcard type: " + type);
}
}
@Nullable private static Type subtypeBound(Type type) {
if (type instanceof WildcardType) {
return subtypeBound((WildcardType) type);
} else {
return type;
}
}
@Nullable private static Type subtypeBound(WildcardType type) {
Type[] lowerBounds = type.getLowerBounds();
if (lowerBounds.length == 1) {
return subtypeBound(lowerBounds[0]);
} else if (lowerBounds.length == 0) {
return null;
} else {
throw new AssertionError(
"Wildcard should have at most one lower bound: " + type);
}
}
@VisibleForTesting static Class getRawType(Type type) {
// For wildcard or type variable, the first bound determines the runtime type.
return getRawTypes(type).iterator().next();
}
@VisibleForTesting static ImmutableSet> getRawTypes(Type type) {
if (type instanceof Class) {
return ImmutableSet.>of((Class) type);
} else if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
// JDK implementation declares getRawType() to return Class: http://goo.gl/YzaEd
return ImmutableSet.>of((Class) parameterizedType.getRawType());
} else if (type instanceof GenericArrayType) {
GenericArrayType genericArrayType = (GenericArrayType) type;
return ImmutableSet.>of(Types.getArrayClass(
getRawType(genericArrayType.getGenericComponentType())));
} else if (type instanceof TypeVariable) {
return getRawTypes(((TypeVariable) type).getBounds());
} else if (type instanceof WildcardType) {
return getRawTypes(((WildcardType) type).getUpperBounds());
} else {
throw new AssertionError(type + " unsupported");
}
}
private static ImmutableSet> getRawTypes(Type[] types) {
ImmutableSet.Builder> builder = ImmutableSet.builder();
for (Type type : types) {
builder.addAll(getRawTypes(type));
}
return builder.build();
}
/**
* Returns the type token representing the generic type declaration of {@code cls}. For example:
* {@code TypeToken.getGenericType(Iterable.class)} returns {@code Iterable}.
*
* If {@code cls} isn't parameterized and isn't a generic array, the type token of the class is
* returned.
*/
@VisibleForTesting static TypeToken toGenericType(Class cls) {
if (cls.isArray()) {
Type arrayOfGenericType = Types.newArrayType(
// If we are passed with int[].class, don't turn it to GenericArrayType
toGenericType(cls.getComponentType()).runtimeType);
@SuppressWarnings("unchecked") // array is covariant
TypeToken result = (TypeToken) of(arrayOfGenericType);
return result;
}
TypeVariable>[] typeParams = cls.getTypeParameters();
if (typeParams.length > 0) {
@SuppressWarnings("unchecked") // Like, it's Iterable for Iterable.class
TypeToken type = (TypeToken)
of(Types.newParameterizedType(cls, typeParams));
return type;
} else {
return of(cls);
}
}
private TypeToken getSupertypeFromUpperBounds(
Class supertype, Type[] upperBounds) {
for (Type upperBound : upperBounds) {
@SuppressWarnings("unchecked") // T's upperbound is .
TypeToken bound = (TypeToken) of(upperBound);
if (of(supertype).isAssignableFrom(bound)) {
@SuppressWarnings({"rawtypes", "unchecked"}) // guarded by the isAssignableFrom check.
TypeToken result = bound.getSupertype((Class) supertype);
return result;
}
}
throw new IllegalArgumentException(supertype + " isn't a super type of " + this);
}
private TypeToken getSubtypeFromLowerBounds(Class subclass, Type[] lowerBounds) {
for (Type lowerBound : lowerBounds) {
@SuppressWarnings("unchecked") // T's lower bound is
TypeToken bound = (TypeToken) of(lowerBound);
// Java supports only one lowerbound anyway.
return bound.getSubtype(subclass);
}
throw new IllegalArgumentException(subclass + " isn't a subclass of " + this);
}
private TypeToken getArraySupertype(Class supertype) {
// with component type, we have lost generic type information
// Use raw type so that compiler allows us to call getSupertype()
@SuppressWarnings("rawtypes")
TypeToken componentType = checkNotNull(getComponentType(),
"%s isn't a super type of %s", supertype, this);
// array is covariant. component type is super type, so is the array type.
@SuppressWarnings("unchecked") // going from raw type back to generics
TypeToken componentSupertype = componentType.getSupertype(supertype.getComponentType());
@SuppressWarnings("unchecked") // component type is super type, so is array type.
TypeToken result = (TypeToken)
// If we are passed with int[].class, don't turn it to GenericArrayType
of(newArrayClassOrGenericArrayType(componentSupertype.runtimeType));
return result;
}
private TypeToken getArraySubtype(Class subclass) {
// array is covariant. component type is subtype, so is the array type.
TypeToken componentSubtype = getComponentType()
.getSubtype(subclass.getComponentType());
@SuppressWarnings("unchecked") // component type is subtype, so is array type.
TypeToken result = (TypeToken)
// If we are passed with int[].class, don't turn it to GenericArrayType
of(newArrayClassOrGenericArrayType(componentSubtype.runtimeType));
return result;
}
private Type resolveTypeArgsForSubclass(Class subclass) {
if (runtimeType instanceof Class) {
// no resolution needed
return subclass;
}
// class Base {}
// class Sub extends Base {}
// Base.subtype(Sub.class):
// Sub.getSupertype(Base.class) => Base
// => X=String, Y=Integer
// => Sub=Sub
TypeToken genericSubtype = toGenericType(subclass);
@SuppressWarnings({"rawtypes", "unchecked"}) // subclass isn't
Type supertypeWithArgsFromSubtype = genericSubtype
.getSupertype((Class) getRawType())
.runtimeType;
return new TypeResolver().where(supertypeWithArgsFromSubtype, runtimeType)
.resolveType(genericSubtype.runtimeType);
}
/**
* Creates an array class if {@code componentType} is a class, or else, a
* {@link GenericArrayType}. This is what Java7 does for generic array type
* parameters.
*/
private static Type newArrayClassOrGenericArrayType(Type componentType) {
return Types.JavaVersion.JAVA7.newArrayType(componentType);
}
private static final class SimpleTypeToken extends TypeToken {
SimpleTypeToken(Type type) {
super(type);
}
private static final long serialVersionUID = 0;
}
/**
* Collects parent types from a sub type.
*
* @param The type "kind". Either a TypeToken, or Class.
*/
private abstract static class TypeCollector {
static final TypeCollector> FOR_GENERIC_TYPE =
new TypeCollector>() {
@Override Class getRawType(TypeToken type) {
return type.getRawType();
}
@Override Iterable> getInterfaces(TypeToken type) {
return type.getGenericInterfaces();
}
@Nullable
@Override TypeToken getSuperclass(TypeToken type) {
return type.getGenericSuperclass();
}
};
static final TypeCollector> FOR_RAW_TYPE =
new TypeCollector>() {
@Override Class getRawType(Class type) {
return type;
}
@Override Iterable> getInterfaces(Class type) {
return Arrays.asList(type.getInterfaces());
}
@Nullable
@Override Class getSuperclass(Class type) {
return type.getSuperclass();
}
};
/** For just classes, we don't have to traverse interfaces. */
final TypeCollector classesOnly() {
return new ForwardingTypeCollector(this) {
@Override Iterable getInterfaces(K type) {
return ImmutableSet.of();
}
@Override ImmutableList collectTypes(Iterable types) {
ImmutableList.Builder builder = ImmutableList.builder();
for (K type : types) {
if (!getRawType(type).isInterface()) {
builder.add(type);
}
}
return super.collectTypes(builder.build());
}
};
}
final ImmutableList collectTypes(K type) {
return collectTypes(ImmutableList.of(type));
}
ImmutableList collectTypes(Iterable types) {
// type -> order number. 1 for Object, 2 for anything directly below, so on so forth.
Map map = Maps.newHashMap();
for (K type : types) {
collectTypes(type, map);
}
return sortKeysByValue(map, Ordering.natural().reverse());
}
/** Collects all types to map, and returns the total depth from T up to Object. */
private int collectTypes(K type, Map map) {
Integer existing = map.get(this);
if (existing != null) {
// short circuit: if set contains type it already contains its supertypes
return existing;
}
int aboveMe = getRawType(type).isInterface()
? 1 // interfaces should be listed before Object
: 0;
for (K interfaceType : getInterfaces(type)) {
aboveMe = Math.max(aboveMe, collectTypes(interfaceType, map));
}
K superclass = getSuperclass(type);
if (superclass != null) {
aboveMe = Math.max(aboveMe, collectTypes(superclass, map));
}
/*
* TODO(benyu): should we include Object for interface?
* Also, CharSequence[] and Object[] for String[]?
*
*/
map.put(type, aboveMe + 1);
return aboveMe + 1;
}
private static ImmutableList sortKeysByValue(
final Map map, final Comparator valueComparator) {
Ordering keyOrdering = new Ordering() {
@Override public int compare(K left, K right) {
return valueComparator.compare(map.get(left), map.get(right));
}
};
return keyOrdering.immutableSortedCopy(map.keySet());
}
abstract Class getRawType(K type);
abstract Iterable getInterfaces(K type);
@Nullable abstract K getSuperclass(K type);
private static class ForwardingTypeCollector extends TypeCollector {
private final TypeCollector delegate;
ForwardingTypeCollector(TypeCollector delegate) {
this.delegate = delegate;
}
@Override Class getRawType(K type) {
return delegate.getRawType(type);
}
@Override Iterable getInterfaces(K type) {
return delegate.getInterfaces(type);
}
@Override K getSuperclass(K type) {
return delegate.getSuperclass(type);
}
}
}
}