Top Description Fields Constructors Methods
com.google.gson.reflect

public Class TypeToken<T>

extends Object
Class Inheritance
Imports
com.google.gson.internal.GsonTypes, .TroubleshootingGuide, java.lang.reflect.GenericArrayType, .ParameterizedType, .Type, .TypeVariable, .WildcardType, java.util.HashMap, .Map, .Objects

Represents a generic type T. Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.

For example, to create a type literal for List<String>, you can create an empty anonymous class:

TypeToken<List<String>> list = new TypeToken<List<String>>() {};

Capturing a type variable as type argument of an anonymous TypeToken subclass is not allowed, for example TypeToken<List<T>>. Due to type erasure the runtime type of a type variable is not available to Gson and therefore it cannot provide the functionality one might expect. This would give a false sense of type-safety at compile time and could lead to an unexpected ClassCastException at runtime.

If the type arguments of the parameterized type are only available at runtime, for example when you want to create a List<E> based on a Class<E> representing the element type, the method getParameterized(Type, Type...) can be used.

Authors
Bob Lee, Sven Mawson, Jesse Wilson

Field Summary

Modifier and TypeField and Description
private final int
private final Class<? super T>
private final Type

Constructor Summary

AccessConstructor and Description
protected
TypeToken()

Constructs a new type literal.

private
TypeToken(Type type)

Unsafe.

Method Summary

Modifier and TypeMethod and Description
private static IllegalArgumentException
buildUnsupportedTypeException(Type token, Class<?>... expected)

public final boolean
equals(Object o)

Overrides java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.

public static TypeToken<?>
get(Type type)

Gets type literal for the given Type instance.

public static <T> TypeToken<T>
get(Class<T> type)

Gets type literal for the given Class instance.

public static TypeToken<?>
getArray(Type componentType)

Gets type literal for the array type whose elements are all instances of componentType.

public static TypeToken<?>
getParameterized(Type rawType, Type... typeArguments)

Gets a type literal for the parameterized type represented by applying typeArguments to rawType.

public final Class<? super T>
getRawType()

Returns the raw (non-generic) type for this type.

public final Type
getType()

Gets underlying Type instance.

private Type
getTypeTokenTypeArgument()

Verifies that this is an instance of a direct subclass of TypeToken and returns the type argument for T in canonical form.

public final int
hashCode()

Overrides java.lang.Object.hashCode.

Returns a hash code value for this object.

public boolean
isAssignableFrom(Class<?> cls)
Deprecated this implementation may be inconsistent with javac for types with wildcards.

Check if this type is assignable from the given class object.

public boolean
isAssignableFrom(Type from)
Deprecated this implementation may be inconsistent with javac for types with wildcards.

Check if this type is assignable from the given Type.

public boolean
isAssignableFrom(TypeToken<?> token)
Deprecated this implementation may be inconsistent with javac for types with wildcards.

Check if this type is assignable from the given type token.

private static boolean
isAssignableFrom(Type from, GenericArrayType to)

Private helper function that performs some assignability checks for the provided GenericArrayType.

private static boolean
isAssignableFrom(Type from, ParameterizedType to, Map<String, Type> typeVarMap)

Private recursive helper function to actually do the type-safe checking of assignability.

private static boolean
private static boolean
matches(Type from, Type to, Map<String, Type> typeMap)

Checks if two types are the same or are equivalent under a variable mapping given in the type map that was provided.

public final String
toString()

Overrides java.lang.Object.toString.

Returns a string representation of the object.

private static boolean
typeEquals(ParameterizedType from, ParameterizedType to, Map<String, Type> typeVarMap)

Checks if two parameterized types are exactly equal, under the variable replacement described in the typeVarMap.

private static void
Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAllwaitwaitwait

Field Detail

hashCodeback to summary
private final int hashCode
rawTypeback to summary
private final Class<? super T> rawType
typeback to summary
private final Type type

Constructor Detail

TypeTokenback to summary
protected TypeToken()

Constructs a new type literal. Derives represented class from type parameter.

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:

new TypeToken<List<String>>() {}

Annotations
@SuppressWarnings:unchecked
Exceptions
IllegalArgumentException:
If the anonymous TypeToken subclass captures a type variable, for example TypeToken<List<T>>. See the TypeToken class documentation for more details.
TypeTokenback to summary
private TypeToken(Type type)

Unsafe. Constructs a type literal manually.

Annotations
@SuppressWarnings:unchecked

Method Detail

buildUnsupportedTypeExceptionback to summary
private static IllegalArgumentException buildUnsupportedTypeException(Type token, Class<?>... expected)
equalsback to summary
public final boolean equals(Object o)

Overrides java.lang.Object.equals.

Doc from java.lang.Object.equals.

Indicates whether some other object is "equal to" this one.

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

An equivalence relation partitions the elements it operates on into equivalence classes; all the members of an equivalence class are equal to each other. Members of an equivalence class are substitutable for each other, at least for some purposes.

Annotations
@Override
getback to summary
public static TypeToken<?> get(Type type)

Gets type literal for the given Type instance.

getback to summary
public static <T> TypeToken<T> get(Class<T> type)

Gets type literal for the given Class instance.

getArrayback to summary
public static TypeToken<?> getArray(Type componentType)

Gets type literal for the array type whose elements are all instances of componentType.

getParameterizedback to summary
public static TypeToken<?> getParameterized(Type rawType, Type... typeArguments)

Gets a type literal for the parameterized type represented by applying typeArguments to rawType. This is mainly intended for situations where the type arguments are not available at compile time. The following example shows how a type token for Map<K, V> can be created:

Class<K> keyClass = ...;
Class<V> valueClass = ...;
TypeToken<?> mapTypeToken = TypeToken.getParameterized(Map.class, keyClass, valueClass);
As seen here the result is a TypeToken<?>; this method cannot provide any type-safety, and care must be taken to pass in the correct number of type arguments.

If rawType is a non-generic class and no type arguments are provided, this method simply delegates to get(Class) and creates a TypeToken(Class).

Exceptions
IllegalArgumentException:
If rawType is not of type Class, or if the type arguments are invalid for the raw type
getRawTypeback to summary
public final Class<? super T> getRawType()

Returns the raw (non-generic) type for this type.

getTypeback to summary
public final Type getType()

Gets underlying Type instance.

getTypeTokenTypeArgumentback to summary
private Type getTypeTokenTypeArgument()

Verifies that this is an instance of a direct subclass of TypeToken and returns the type argument for T in canonical form.

hashCodeback to summary
public final int hashCode()

Overrides java.lang.Object.hashCode.

Doc from java.lang.Object.hashCode.

Returns a hash code value for this object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Annotations
@Override
isAssignableFromback to summary
public boolean isAssignableFrom(Class<?> cls)

Deprecated

this implementation may be inconsistent with javac for types with wildcards.

Check if this type is assignable from the given class object.

Annotations
@Deprecated
isAssignableFromback to summary
public boolean isAssignableFrom(Type from)

Deprecated

this implementation may be inconsistent with javac for types with wildcards.

Check if this type is assignable from the given Type.

Annotations
@Deprecated
isAssignableFromback to summary
public boolean isAssignableFrom(TypeToken<?> token)

Deprecated

this implementation may be inconsistent with javac for types with wildcards.

Check if this type is assignable from the given type token.

Annotations
@Deprecated
isAssignableFromback to summary
private static boolean isAssignableFrom(Type from, GenericArrayType to)

Private helper function that performs some assignability checks for the provided GenericArrayType.

isAssignableFromback to summary
private static boolean isAssignableFrom(Type from, ParameterizedType to, Map<String, Type> typeVarMap)

Private recursive helper function to actually do the type-safe checking of assignability.

isCapturingTypeVariablesForbiddenback to summary
private static boolean isCapturingTypeVariablesForbidden()
matchesback to summary
private static boolean matches(Type from, Type to, Map<String, Type> typeMap)

Checks if two types are the same or are equivalent under a variable mapping given in the type map that was provided.

toStringback to summary
public final String toString()

Overrides java.lang.Object.toString.

Doc from java.lang.Object.toString.

Returns a string representation of the object. Satisfying this method's contract implies a non-null result must be returned.

Annotations
@Override
typeEqualsback to summary
private static boolean typeEquals(ParameterizedType from, ParameterizedType to, Map<String, Type> typeVarMap)

Checks if two parameterized types are exactly equal, under the variable replacement described in the typeVarMap.

verifyNoTypeVariableback to summary
private static void verifyNoTypeVariable(Type type)