Java Reflection and Generics: Class<T>, Type Tokens and the Type Interface
Learn what reflection can reveal about Java generics despite erasure: the generic Class<T> class, matching Class<T> parameters, the Type interface with TypeVariable, WildcardType, ParameterizedType and GenericArrayType, and type literals (super type tokens) for generic types.
kvi5hnuCode Sprout team member10 min readOn this page
Reflection lets you analyze arbitrary objects at run time. With generic classes, erasure means you don't learn much about the type arguments of a particular object: a Pair<String> instance doesn't know it holds strings. But that's not the whole story. Classes still remember their generic declarations, and Class itself is generic, which makes reflective code more type-safe. This article shows what you can and can't find out, and a clever trick, the type literal, that frameworks use to work with generic types at run time.
The generic Class class
Class has a type parameter. String.class is an object, in fact the only object, of type Class<String>.
The type parameter makes several methods of Class<T> more precise about their return types:
T cast(Object obj)
T[] getEnumConstants()
Class<? super T> getSuperclass()
Constructor<T> getConstructor(Class<?>... parameterTypes)
Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
Because getConstructor returns a Constructor<T>, no cast is needed:
Class<T> cl = . . .;
T noArgInstance = cl.getConstructor().newInstance();
castreturns the given object, now typed asT, if it isnullor really is aT. Otherwise it throws aClassCastException. It's the reflective counterpart of a cast, useful when the type is only known through aClassobject.getEnumConstantsreturns an array of all the values ifTis an enum type, andnullotherwise.getSuperclassreturns the superclass, ornullifTisn't a class or isObject. Its type,Class<? super T>, says it's some supertype ofT.
Using Class<T> parameters for type matching
It's often useful to match the type variable of a Class<T> parameter in a generic method. Here is the classic example:
public static <T> Pair<T> makePair(Class<T> c) throws ReflectiveOperationException {
Constructor<T> constr = c.getConstructor();
return new Pair<>(constr.newInstance(), constr.newInstance());
}
When you call makePair(StringBuilder.class), StringBuilder.class has type Class<StringBuilder>. So T matches StringBuilder, and the compiler infers that the method returns a Pair<StringBuilder>. A Class<T> used this way is sometimes called a type token. You'll see the pattern throughout the JDK and frameworks, for example in EnumSet.noneOf(DayOfWeek.class) and ServiceLoader.load(Service.class).
Generic type information in the virtual machine
A notable feature of Java generics is that types are erased in the VM. Perhaps surprisingly, the erased classes still keep a faint memory of their generic origin. The raw Pair class knows that it came from the generic class Pair<T>, even though a Pair object can't tell whether it was constructed as a Pair<String> or a Pair<Employee>.
Similarly, consider the method
public static Comparable min(Comparable[] a)
which is the erasure of the generic method
public static <T extends Comparable<? super T>> T min(T[] a)
Using the reflection API, you can find out that:
- the generic method has a type parameter called
T; - the type parameter has a subtype bound that is itself a generic type;
- the bounding type has a wildcard parameter;
- the wildcard has a supertype bound; and
- the method has a generic array parameter.
In other words, you can reconstruct everything about generic classes and methods that their implementors declared. What you can't find out is how the type parameters were resolved for specific objects or method calls.
The Type interface
Generic type declarations are expressed with the interface java.lang.reflect.Type. It has these subtypes:
- the
Classclass, for concrete types; TypeVariable, for type variables, such asT extends Comparable<? super T>;WildcardType, for wildcards, such as? super T;ParameterizedType, for generic class or interface types, such asComparable<? super T>;GenericArrayType, for generic arrays, such asT[].
![Diagram of the Type interface with its subtypes Class, TypeVariable, WildcardType, ParameterizedType and GenericArrayType, and how the declaration static <T extends Comparable<? super T>> T min(T[] a) breaks down into them](https://code-sprout-content.laxmi.solutions/asset/2026/11/a4tprl7rtfbadbdp.png)
The last four are interfaces. The virtual machine instantiates suitable classes that implement them. To get these objects, call the "generic" variants of the reflection methods: Class.getTypeParameters, getGenericSuperclass, getGenericInterfaces, Method.getGenericReturnType, getGenericParameterTypes and Field.getGenericType.
The demo's GenericPrinter walks these objects recursively and prints declarations in source-like form. For Pair it reports
class Pair<T>
public T getFirst()
public T getSecond()
public void setFirst(T)
public void setSecond(T)
and for ArrayAlg it reconstructs the full generic signature of minmax:
public static <T extends Comparable<? super T>> Pair<T> minmax(T[])
printType handles each kind of Type with a pattern-matching instanceof:
- a
Classprints its name; - a
TypeVariableprints its name, plus its bounds in a definition; - a
WildcardTypeprints?with any upper (extends) and lower (super) bounds; - a
ParameterizedTypeprints its owner (for inner classes), raw type and type arguments; - a
GenericArrayTypeprints its component type followed by[].
Type literals
Sometimes you want a program's behavior to depend on the type of a value. A persistence or serialization library might let users register how objects of a certain class are saved. That's normally done by associating a Class object with an action.
With generic classes, erasure gets in the way. How can you register different actions for ArrayList<Integer> and ArrayList<String> when both erase to the same raw ArrayList?
A trick offers relief in some situations. You can capture an instance of the Type interface from the previous section by constructing an anonymous subclass:
var type = new TypeLiteral<ArrayList<Integer>>() {}; // note the {}
The TypeLiteral constructor captures the generic supertype:
class TypeLiteral<T> {
private Type type;
public TypeLiteral() {
Type parentType = getClass().getGenericSuperclass();
if (parentType instanceof ParameterizedType paramType)
type = paramType.getActualTypeArguments()[0];
else
throw new UnsupportedOperationException("Construct as new TypeLiteral<. . .>() {}");
}
. . .
}
Why does this work? The anonymous class is a real class, compiled with the declared superclass TypeLiteral<ArrayList<Integer>>. Superclass declarations are kept in the class file, so getGenericSuperclass returns a ParameterizedType whose type argument is exactly ArrayList<Integer>. Without the {}, there's no subclass, so no recorded type argument, and the constructor throws.
If a generic type is available at run time, you can match it against a TypeLiteral. You can't get a generic type from an object, since that's erased. But, as you saw, the generic types of fields and method parameters survive in the class files.
The demo uses this to format an object's fields. It enumerates the fields, whose generic types are available through Field.getGenericType(), and looks up a formatting rule for each type:
- an
ArrayList<Integer>is formatted as numbers separated by spaces; - an
ArrayList<Character>is joined into a quoted string; - any other list uses
ArrayList.toString.
TypeLiteral implements equals and hashCode by comparing the captured Type objects, so it can be used as a key in a HashMap.
A complete example
import java.lang.reflect.*;
import java.time.DayOfWeek;
import java.util.*;
import java.util.function.*;
public class Solution {
public static void main(String[] args) throws Exception {
// 1. Class<T> makes reflection methods type-safe
Class<String> cl = String.class;
Object o = "hello";
String s = cl.cast(o); // no (String) cast needed
System.out.println("cast: " + s.toUpperCase());
DayOfWeek[] days = DayOfWeek.class.getEnumConstants();
System.out.println("enum constants: " + days.length + ", first " + days[0]);
System.out.println("String is not an enum: " + String.class.getEnumConstants());
Class<? super Integer> sup = Integer.class.getSuperclass();
System.out.println("superclass of Integer: " + sup.getSimpleName());
StringBuilder sb = StringBuilder.class.getConstructor(String.class).newInstance("built");
System.out.println("constructed: " + sb.reverse());
// 2. matching the type parameter of a Class<T> argument
Pair<StringBuilder> p = makePair(StringBuilder.class);
p.getFirst().append("first");
System.out.println("makePair: " + p.getFirst() + ", \"" + p.getSecond() + "\"");
// 3. the declared generic information survives in class files
GenericPrinter.printClass(Pair.class);
GenericPrinter.printClass(ArrayAlg.class);
GenericPrinter.printClass(Names.class);
// 4. type literals: tell ArrayList<Integer> and ArrayList<Character> apart
var formatter = new FieldFormatter();
formatter.forType(new TypeLiteral<ArrayList<Integer>>() {}, lst -> join(" ", lst));
formatter.forType(new TypeLiteral<ArrayList<Character>>() {}, lst -> "\"" + join("", lst) + "\"");
System.out.print(formatter.formatFields(new Sample()));
System.out.println(new TypeLiteral<Map<String, List<Integer>>>() {});
}
public static <T> Pair<T> makePair(Class<T> c) throws ReflectiveOperationException {
Constructor<T> constr = c.getConstructor();
return new Pair<>(constr.newInstance(), constr.newInstance());
}
private static <T> String join(String separator, ArrayList<T> elements) {
var result = new StringBuilder();
for (T e : elements) {
if (result.length() > 0) result.append(separator);
result.append(e.toString());
}
return result.toString();
}
}
class Pair<T> {
private T first;
private T second;
public Pair(T first, T second) { this.first = first; this.second = second; }
public T getFirst() { return first; }
public T getSecond() { return second; }
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }
}
class ArrayAlg {
public static <T extends Comparable<? super T>> Pair<T> minmax(T[] a) {
T min = a[0], max = a[0];
for (T t : a) {
if (t.compareTo(min) < 0) min = t;
if (t.compareTo(max) > 0) max = t;
}
return new Pair<>(min, max);
}
}
abstract class Names extends AbstractList<String> implements Comparable<Names> { }
/** Prints the generic declarations of a class and its declared methods. */
class GenericPrinter {
static void printClass(Class<?> cl) {
System.out.print(cl);
printTypes(cl.getTypeParameters(), "<", ", ", ">", true);
Type sc = cl.getGenericSuperclass();
if (sc != null && sc != Object.class) {
System.out.print(" extends ");
printType(sc, false);
}
printTypes(cl.getGenericInterfaces(), " implements ", ", ", "", false);
System.out.println();
Arrays.stream(cl.getDeclaredMethods())
.sorted(Comparator.comparing(Method::getName))
.forEach(GenericPrinter::printMethod);
}
static void printMethod(Method m) {
System.out.print(" " + Modifier.toString(m.getModifiers()) + " ");
printTypes(m.getTypeParameters(), "<", ", ", "> ", true);
printType(m.getGenericReturnType(), false);
System.out.print(" " + m.getName() + "(");
printTypes(m.getGenericParameterTypes(), "", ", ", "", false);
System.out.println(")");
}
static void printTypes(Type[] types, String pre, String sep, String suf, boolean isDefinition) {
if (pre.equals(" extends ") && Arrays.equals(types, new Type[] { Object.class })) return;
if (types.length > 0) System.out.print(pre);
for (int i = 0; i < types.length; i++) {
if (i > 0) System.out.print(sep);
printType(types[i], isDefinition);
}
if (types.length > 0) System.out.print(suf);
}
static void printType(Type type, boolean isDefinition) {
if (type instanceof Class<?> t) {
System.out.print(t.getSimpleName());
} else if (type instanceof TypeVariable<?> t) {
System.out.print(t.getName());
if (isDefinition) printTypes(t.getBounds(), " extends ", " & ", "", false);
} else if (type instanceof WildcardType t) {
System.out.print("?");
printTypes(t.getUpperBounds(), " extends ", " & ", "", false);
printTypes(t.getLowerBounds(), " super ", " & ", "", false);
} else if (type instanceof ParameterizedType t) {
Type owner = t.getOwnerType();
if (owner != null) {
printType(owner, false);
System.out.print(".");
}
printType(t.getRawType(), false);
printTypes(t.getActualTypeArguments(), "<", ", ", ">", false);
} else if (type instanceof GenericArrayType t) {
printType(t.getGenericComponentType(), isDefinition);
System.out.print("[]");
}
}
}
/** A type literal describes a type that can be generic, such as ArrayList<String>. */
class TypeLiteral<T> {
private final Type type;
/** Must be invoked from an anonymous subclass: new TypeLiteral<. . .>() {} */
public TypeLiteral() {
Type parentType = getClass().getGenericSuperclass();
if (parentType instanceof ParameterizedType paramType)
type = paramType.getActualTypeArguments()[0];
else
throw new UnsupportedOperationException("Construct as new TypeLiteral<. . .>() {}");
}
private TypeLiteral(Type type) { this.type = type; }
/** Yields a type literal that describes the given type. */
public static TypeLiteral<?> of(Type type) { return new TypeLiteral<Object>(type); }
@Override public String toString() {
return type instanceof Class<?> cl ? cl.getName() : type.getTypeName();
}
@Override public boolean equals(Object other) {
return other instanceof TypeLiteral<?> lit && type.equals(lit.type);
}
@Override public int hashCode() { return type.hashCode(); }
}
/** Formats objects, using rules that associate types with formatting functions. */
class FieldFormatter {
private final Map<TypeLiteral<?>, Function<?, String>> rules = new HashMap<>();
public <T> void forType(TypeLiteral<T> type, Function<T, String> formatterForType) {
rules.put(type, formatterForType);
}
public String formatFields(Object obj) throws IllegalAccessException {
var result = new StringBuilder();
Field[] fields = obj.getClass().getDeclaredFields();
Arrays.sort(fields, Comparator.comparing(Field::getName));
for (Field f : fields) {
result.append(f.getName()).append("=");
f.setAccessible(true);
Function<?, String> formatterForType = rules.get(TypeLiteral.of(f.getGenericType()));
if (formatterForType != null) {
// the parameter type of formatterForType is the field's type; erase it to call apply
@SuppressWarnings("unchecked")
var objectFormatter = (Function<Object, String>) formatterForType;
result.append(objectFormatter.apply(f.get(obj)));
} else {
result.append(f.get(obj));
}
result.append("\n");
}
return result.toString();
}
}
class Sample {
ArrayList<Integer> nums = new ArrayList<>(List.of(42, 1729));
ArrayList<Character> chars = new ArrayList<>(List.of('H', 'i'));
ArrayList<String> strings = new ArrayList<>(List.of("Hello", "World"));
}
cast: HELLO
enum constants: 7, first MONDAY
String is not an enum: null
superclass of Integer: Number
constructed: tliub
makePair: first, ""
class Pair<T>
public T getFirst()
public T getSecond()
public void setFirst(T)
public void setSecond(T)
class ArrayAlg
public static <T extends Comparable<? super T>> Pair<T> minmax(T[])
class Names extends AbstractList<String> implements Comparable<Names>
chars="Hi"
nums=42 1729
strings=[Hello, World]
java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>
The last line prints a type literal for Map<String, List<Integer>>. The full generic type was captured, even though no object of that type exists.
API reference
java.lang.Class<T>
| Method | Description |
|---|---|
T cast(Object obj) | Returns obj if it is null or converts to T. Otherwise throws ClassCastException |
T[] getEnumConstants() | All values if T is an enum type, otherwise null |
Class<? super T> getSuperclass() | The superclass, or null if T isn't a class or is Object |
Constructor<T> getConstructor(Class<?>... parameterTypes), getDeclaredConstructor(...) | The public constructor, or any constructor, with the given parameter types |
TypeVariable[] getTypeParameters() | The type variables of a generic declaration, or an empty array |
Type getGenericSuperclass() | The generic superclass type, or null for Object and non-class types |
Type[] getGenericInterfaces() | The generic interface types, in declaration order, or an empty array |
java.lang.reflect.Method
| Method | Description |
|---|---|
TypeVariable[] getTypeParameters() | The type variables of a generic method, or an empty array |
Type getGenericReturnType() | The generic return type |
Type[] getGenericParameterTypes() | The generic parameter types, or an empty array |
java.lang.reflect.Field has Type getGenericType().
TypeVariable: String getName() returns the name. Type[] getBounds() returns the subclass bounds, or an empty array if unbounded.
WildcardType: Type[] getUpperBounds() returns the extends bounds. Type[] getLowerBounds() returns the super bounds, or an empty array.
ParameterizedType: Type getRawType() returns the raw type. Type[] getActualTypeArguments() returns the type arguments. Type getOwnerType() returns the outer class type for inner types, or null for top-level types.
GenericArrayType: Type getGenericComponentType() returns the generic component type.
Where to go from here
You now know how to use generic classes, how to write your own generic classes and methods when needed, and, just as important, how to read the generic declarations in API documentation and error messages. For an exhaustive discussion of nearly every question about Java generics, Angelika Langer's Java Generics FAQ (angelikalanger.com) is the classic reference.
Next, the collections framework, where generics do their most important work.
Common questions
Can I find out at run time that a list was created as ArrayList<String>?
No. The type argument of an object is erased. You can only find the generic types that were declared somewhere: in a field, a method parameter or return type, or a superclass, for example through Field.getGenericType().
What is a type token?
A Class<T> object passed to a method so that the method knows T at run time, as in EnumSet.noneOf(Day.class). It only works for non-generic types, because there is no List<String>.class. For generic types, frameworks use a "super type token", an anonymous subclass such as new TypeReference<List<String>>() {}.
Why does a type literal need the braces {}?
The braces create an anonymous subclass, whose class file records the superclass TypeLiteral<ArrayList<Integer>> with its type argument. Without them, you'd just construct a TypeLiteral object, and no type argument would be stored anywhere.
What is the difference between getSuperclass() and getGenericSuperclass()?
getSuperclass() returns the raw Class of the superclass. getGenericSuperclass() returns a Type, which is a ParameterizedType with the type arguments if the superclass was declared with them.
Is there a simple way to print a generic signature?
Yes. Method.toGenericString(), Class.toGenericString() and Type.getTypeName() produce readable descriptions. Walking the Type objects yourself is only needed when you want to act on the individual parts.
Summary
Class<T>is generic.cast,getEnumConstants,getSuperclassandgetConstructorreturn precisely typed results.- A
Class<T>parameter, a type token, lets a generic method inferTfrom a class literal, as inmakePair(String.class). - Objects don't remember type arguments, but class files keep generic declarations: type parameters, generic superclasses and interfaces, and generic field, parameter and return types.
- These are represented by
Type:Class,TypeVariable,WildcardType,ParameterizedTypeandGenericArrayType. - A type literal,
new TypeLiteral<ArrayList<Integer>>() {}, captures a full generic type through an anonymous subclass's generic superclass. Frameworks such as Guice, Jackson and Gson rely on this technique.
Practice Questions
What is the type of Integer.class, and what does Integer.class.cast(o) return?
Class<Integer>. cast returns o typed as Integer if it is null or an Integer, and throws a ClassCastException otherwise.
Given an object list of type ArrayList<String>, can reflection tell you that its element type is String?
No. The object's class is just ArrayList, and type arguments aren't stored in objects. If list is a field declared as ArrayList<String>, Field.getGenericType() reveals the declared type.
Which Type subinterface represents each of these: T, ? extends Number, List<String>, T[], int?
TypeVariable, WildcardType, ParameterizedType, GenericArrayType, and Class (int.class).
Why does new TypeLiteral<List<String>>() {} work, but new TypeLiteral<List<String>>() throw an exception?
The {} creates an anonymous subclass whose declared superclass TypeLiteral<List<String>> is recorded in the class file, so getGenericSuperclass returns a ParameterizedType with the argument List<String>. Without {}, the object is a plain TypeLiteral, whose superclass is Object, so there's no type argument to capture.
Write a generic method that creates an empty array of a given class's type, of a given length.
@SuppressWarnings("unchecked") static <T> T[] newArray(Class<T> cl, int n) { return (T[]) java.lang.reflect.Array.newInstance(cl, n); }. For example, newArray(String.class, 3) returns a String[3].
Previous: Java Generics Restrictions and Limitations: What You Can't Do with Type Parameters
Next: The Java Collections Framework: Interfaces, Implementations and Iterators
Related reading
- Java Generics Inheritance Rules and Wildcards: extends, super and ?
- Java Generics: Generic Classes and Generic Methods
- Java Reflection: Invoking Methods and Writing Generic Array Code
- Java Reflection: Analyzing Classes and Inspecting Objects at Runtime
- Java Reflection: The Class Class, Exceptions Primer and Loading Resources

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.