Class TypeToken<T>
-
- com.google.common.reflect.TypeToken<T>
-
- All Implemented Interfaces:
@Beta public abstract class TypeToken<T> extends implements
A with generics.Operations that are otherwise only available in are implemented to support
Type
, for exampleisSubtypeOf(com.google.common.reflect.TypeToken<?>)
,isArray()
andgetComponentType()
. It also provides additional utilities such asgetTypes()
,resolveType(java.lang.reflect.Type)
, etc.There are three ways to get a
TypeToken
instance:- Wrap a
Type
obtained via reflection. For example:TypeToken.of(method.getGenericReturnType())
. - Capture a generic type with a (usually anonymous) subclass. For example:
new TypeToken<List<String>>() {}
Note that it's critical that the actual type argument is carried by a subclass. The following code is wrong because it only captures the
<T>
type variable of thelistType()
method signature; while<String>
is lost in erasure:class Util { static <T> TypeToken<List<T>> listType() { return new TypeToken<List<T>>() {}; } } TypeToken<List<String>> stringListType = Util.<String>listType();
- Capture a generic type with a (usually anonymous) subclass and resolve it against a context
class that knows what the type parameters are. For example:
abstract class IKnowMyType<T> { TypeToken<T> type = new TypeToken<T>(getClass()) {}; } new IKnowMyType<String>() {}.type => String
TypeToken
is serializable when no type variable is contained in the type.Note to Guice users: TypeToken is similar to Guice's
TypeLiteral
class except that it is serializable and offers numerous additional utility methods.- Since:
- 12.0
- Author:
- Bob Lee, Sven Mawson, Ben Yu
- See Also:
- Serialized Form
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description class
TypeToken.TypeSet
The set of interfaces and classes thatT
is or is a subtype of.
-
Constructor Summary
Constructors Modifier Constructor Description protected
TypeToken()
Constructs a new type token ofT
.protected
<?> declaringClass)
Constructs a new type token ofT
while resolving free type variables in the context ofdeclaringClass
.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description Invokable<T,T>
<?> constructor)
boolean
o)
Returns true ifo
is anotherTypeToken
that represents the same .TypeToken<?>
getComponentType()
Returns the array component type if this type represents an array (int[]
,T[]
,<? extends Map<String, Integer>[]>
etc.), or elsenull
is returned.<? super T>
getRawType()
Returns the raw type ofT
.TypeToken<? extends T>
<?> subclass)
Returns subtype ofthis
withsubclass
as the raw class.TypeToken<? super T>
<? super T> superclass)
Returns the generic form ofsuperclass
.getType()
Returns the represented type.TypeToken.TypeSet
getTypes()
Returns the set of interfaces and classes that this type is or is a subtype of.int
hashCode()
Returns a hash code value for the object.boolean
isArray()
Returns true if this type is known to be an array type, such asint[]
,T[]
,<? extends Map<String, Integer>[]>
etc.boolean
isPrimitive()
Returns true if this type is one of the nine primitive types (includingvoid
).boolean
isSubtypeOf(TypeToken<?> type)
Returns true if this type is a subtype of the giventype
.boolean
supertype)
Returns true if this type is a subtype of the giventype
.boolean
isSupertypeOf(TypeToken<?> type)
Returns true if this type is a supertype of the giventype
.boolean
type)
Returns true if this type is a supertype of the giventype
.>
method)
static <T> TypeToken<T>
<T> type)
Returns an instance of type token that wrapstype
.static TypeToken<?>
type)
Returns an instance of type token that wrapstype
.TypeToken<?>
type)
Resolves the giventype
against the type context represented by this type.toString()
Returns a string representation of the object.TypeToken<T>
unwrap()
Returns the corresponding primitive type if this is a wrapper type; otherwise returnsthis
itself.<X> TypeToken<T>
where(TypeParameter<X> typeParam, TypeToken<X> typeArg)
Returns a newTypeToken
where type variables represented bytypeParam
are substituted bytypeArg
.<X> TypeToken<T>
where(TypeParameter<X> typeParam, <X> typeArg)
Returns a newTypeToken
where type variables represented bytypeParam
are substituted bytypeArg
.TypeToken<T>
wrap()
Returns the corresponding wrapper type if this is a primitive type; otherwise returnsthis
itself.protected
writeReplace()
Implemented to support serialization of subclasses.
-
-
-
Constructor Detail
-
TypeToken
protected TypeToken()
Constructs a new type token ofT
.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:
TypeToken<List<String>> t = new TypeToken<List<String>>() {};
-
TypeToken
protected <?> declaringClass)
Constructs a new type token ofT
while resolving free type variables in the context ofdeclaringClass
.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:
abstract class IKnowMyType<T> { TypeToken<T> getMyType() { return new TypeToken<T>(getClass()) {}; } } new IKnowMyType<String>() {}.getMyType() => String
-
-
Method Detail
-
of
public static <T> <T> type)
Returns an instance of type token that wrapstype
.
-
of
public static type)
Returns an instance of type token that wrapstype
.
-
getRawType
public final <? super T> getRawType()
Returns the raw type ofT
. Formally speaking, ifT
is returned by , the raw type is what's returned by of the same method object. Specifically:- If
T
is aClass
itself,T
itself is returned. - If
T
is a , the raw type of the parameterized type is returned. - If
T
is a , the returned type is the corresponding array class. For example:List<Integer>[] => List[]
. - If
T
is a type variable or a wildcard type, the raw type of the first upper bound is returned. For example:<X extends Foo> => Foo
.
- If
-
getType
public final getType()
Returns the represented type.
-
where
public final <X> TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg)
Returns a newTypeToken
where type variables represented bytypeParam
are substituted bytypeArg
. For example, it can be used to constructMap<K, V>
for anyK
andV
type:static <K, V> TypeToken<Map<K, V>> mapOf( TypeToken<K> keyType, TypeToken<V> valueType) { return new TypeToken<Map<K, V>>() {} .where(new TypeParameter<K>() {}, keyType) .where(new TypeParameter<V>() {}, valueType); }
- Type Parameters:
X
- The parameter type- Parameters:
typeParam
- the parameter type variabletypeArg
- the actual type to substitute
-
where
public final <X> TypeToken<T> where(TypeParameter<X> typeParam, <X> typeArg)
Returns a newTypeToken
where type variables represented bytypeParam
are substituted bytypeArg
. For example, it can be used to constructMap<K, V>
for anyK
andV
type:static <K, V> TypeToken<Map<K, V>> mapOf( Class<K> keyType, Class<V> valueType) { return new TypeToken<Map<K, V>>() {} .where(new TypeParameter<K>() {}, keyType) .where(new TypeParameter<V>() {}, valueType); }
- Type Parameters:
X
- The parameter type- Parameters:
typeParam
- the parameter type variabletypeArg
- the actual type to substitute
-
resolveType
public final type)
Resolves the giventype
against the type context represented by this type. For example:new TypeToken<List<String>>() {}.resolveType( List.class.getMethod("get", int.class).getGenericReturnType()) => String.class
-
getTypes
public final TypeToken.TypeSet getTypes()
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).
-
getSupertype
public final <? super T> superclass)
Returns the generic form ofsuperclass
. For example, if this isArrayList<String>
,Iterable<String>
is returned given the inputIterable.class
.
-
getSubtype
public final <?> subclass)
Returns subtype ofthis
withsubclass
as the raw class. For example, if this isIterable<String>
andsubclass
isList
,List<String>
is returned.
-
isSupertypeOf
public final boolean isSupertypeOf(TypeToken<?> type)
Returns true if this type is a supertype of the giventype
. "Supertype" is defined according to introduced with Java generics.- Since:
- 19.0
-
isSupertypeOf
public final boolean type)
Returns true if this type is a supertype of the giventype
. "Supertype" is defined according to introduced with Java generics.- Since:
- 19.0
-
isSubtypeOf
public final boolean isSubtypeOf(TypeToken<?> type)
Returns true if this type is a subtype of the giventype
. "Subtype" is defined according to introduced with Java generics.- Since:
- 19.0
-
isSubtypeOf
public final boolean supertype)
Returns true if this type is a subtype of the giventype
. "Subtype" is defined according to introduced with Java generics.- Since:
- 19.0
-
isArray
public final boolean isArray()
Returns true if this type is known to be an array type, such asint[]
,T[]
,<? extends Map<String, Integer>[]>
etc.
-
isPrimitive
public final boolean isPrimitive()
Returns true if this type is one of the nine primitive types (includingvoid
).- Since:
- 15.0
-
wrap
public final TypeToken<T> wrap()
Returns the corresponding wrapper type if this is a primitive type; otherwise returnsthis
itself. Idempotent.- Since:
- 15.0
-
unwrap
public final TypeToken<T> unwrap()
Returns the corresponding primitive type if this is a wrapper type; otherwise returnsthis
itself. Idempotent.- Since:
- 15.0
-
getComponentType
public final TypeToken<?> getComponentType()
Returns the array component type if this type represents an array (int[]
,T[]
,<? extends Map<String, Integer>[]>
etc.), or elsenull
is returned.
-
method
public final > method)
- Since:
- 14.0
-
constructor
public final <?> constructor)
- Since:
- 14.0
-
equals
public boolean o)
Returns true ifo
is anotherTypeToken
that represents the same .- Overrides:
in class
- Parameters:
o
- the reference object with which to compare.- Returns:
true
if this object is the same as the obj argument;false
otherwise.- See Also:
- ,
-
hashCode
public int hashCode()
Description copied from class:Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by .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 inequals
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(Object)
method, then calling thehashCode
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
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.
As much as is reasonably practical, the hashCode method defined by class
Object
does return distinct integers for distinct objects. (The hashCode may or may not be implemented as some function of an object's memory address at some point in time.)- Overrides:
in class
- Returns:
- a hash code value for this object.
- See Also:
- ,
- Whenever it is invoked on the same object more than once during
an execution of a Java application, the
-
toString
public toString()
Description copied from class:Returns a string representation of the object. In general, thetoString
method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.The
toString
method for classObject
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@
', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:getClass().getName() + '@' + Integer.toHexString(hashCode())
- Overrides:
in class
- Returns:
- a string representation of the object.
-
writeReplace
protected writeReplace()
Implemented to support serialization of subclasses.
-
-