Sub topic 12
Generic Type Information and Type Erasure
This chapter assumes you know how to write generic classes and methods, how to get a Class object, and how to read a Field or Method through reflection. It covers what the compiler removes from generic types, what it keeps, and how to read the part that remains.
What type erasure removes
The compiler checks generic types and then erases them. A List<String> and a List<Integer> are both plain ArrayList objects at runtime. The object does not remember which type argument it was created with.
import java.util.ArrayList;
import java.util.List;
public class ErasureDemo {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
List<Integer> numbers = new ArrayList<>();
System.out.println(strings.getClass() == numbers.getClass());
System.out.println(strings.getClass().getTypeParameters()[0]);
@SuppressWarnings({"unchecked", "rawtypes"})
List<Object> raw = (List) strings;
raw.add(42);
try {
String s = strings.get(0);
} catch (ClassCastException e) {
System.out.println("ClassCastException at the read");
}
}
}The program prints true, then E, then ClassCastException at the read.
- The two lists share one class, so no reflective call can tell them apart.
getTypeParameters()returns the declared parameterEofArrayList. It does not returnString.- The raw cast lets an
Integerinto a list that is declared to hold strings. The failure appears later, at the read, where the compiler inserted a cast toString.
What the class file keeps
Erasure applies to the bytecode that runs. The compiler still writes the generic declarations into the class file, in an attribute called Signature. Reflection can read that attribute for these declarations:
- field types
- method return types
- method parameter types
- type parameters of classes and methods, with their bounds
- the superclass and the interfaces of a class
Values and local variables carry no such information. Only declarations do.
Class versus Type
Each reflective member has two accessors, one that returns the erased type and one that returns the generic type.
| Member | Erased accessor | Generic accessor |
|---|---|---|
| `Field` | `getType()` | `getGenericType()` |
| `Method` | `getReturnType()` | `getGenericReturnType()` |
| `Method` | `getParameterTypes()` | `getGenericParameterTypes()` |
| `Class` | `getSuperclass()` | `getGenericSuperclass()` |
| `Class` | `getInterfaces()` | `getGenericInterfaces()` |
For a field declared as List<String> names, getType() returns List.class. getGenericType() returns a java.lang.reflect.Type.
Type is a small interface with several kinds of implementation, and you must test which kind you have received:
| Implementation | Represents | Example |
|---|---|---|
| `Class` | A plain or raw type | `String`, `int`, `List` |
| `ParameterizedType` | A type with arguments | `Map<String, Integer>` |
| `TypeVariable` | A declared variable | `T` |
| `WildcardType` | A wildcard with bounds | `? extends Number` |
| `GenericArrayType` | An array of a generic type | `T[]`, `List<String>[]` |
The first example from the plan reads one parameterized field:
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
class Holder {
List<String> names;
}
public class GenericDemo {
public static void main(String[] args) throws Exception {
Field f = Holder.class.getDeclaredField("names");
Type t = f.getGenericType();
if (t instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) t;
System.out.println(pt.getRawType());
System.out.println(pt.getActualTypeArguments()[0]);
}
}
}It prints interface java.util.List and class java.lang.String. getRawType() gives the type that carries the arguments. getActualTypeArguments() gives one Type for each argument. Each argument can itself be parameterized, so nested types need recursion.
Walking nested types
The next program describes any Type by checking its kind and recursing into its parts. It reads one field, a method with a wildcard, and a method with its own type variable.
import java.lang.reflect.Field;
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.List;
import java.util.Map;
import java.util.Set;
class Service {
Map<String, List<Integer>> scores;
public List<? extends Number> numbers(Set<String> keys) {
return null;
}
public <T extends Comparable<T>> T[] sorted(List<T> items) {
return null;
}
}
public class TypeWalker {
static String describe(Type t) {
if (t instanceof Class<?>) {
return ((Class<?>) t).getSimpleName();
}
if (t instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) t;
StringBuilder sb = new StringBuilder(describe(pt.getRawType())).append('<');
Type[] args = pt.getActualTypeArguments();
for (int i = 0; i < args.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(describe(args[i]));
}
return sb.append('>').toString();
}
if (t instanceof WildcardType) {
WildcardType w = (WildcardType) t;
if (w.getLowerBounds().length > 0) {
return "? super " + describe(w.getLowerBounds()[0]);
}
Type upper = w.getUpperBounds()[0];
return upper == Object.class ? "?" : "? extends " + describe(upper);
}
if (t instanceof TypeVariable<?>) {
return ((TypeVariable<?>) t).getName();
}
if (t instanceof GenericArrayType) {
return describe(((GenericArrayType) t).getGenericComponentType()) + "[]";
}
return t.getTypeName();
}
public static void main(String[] args) throws Exception {
Field scores = Service.class.getDeclaredField("scores");
System.out.println("scores: " + describe(scores.getGenericType()));
Method numbers = Service.class.getMethod("numbers", Set.class);
System.out.println("numbers returns: " + describe(numbers.getGenericReturnType()));
System.out.println("numbers param: " + describe(numbers.getGenericParameterTypes()[0]));
Method sorted = Service.class.getMethod("sorted", List.class);
System.out.println("sorted returns: " + describe(sorted.getGenericReturnType()));
System.out.println("sorted param: " + describe(sorted.getGenericParameterTypes()[0]));
TypeVariable<Method> tv = sorted.getTypeParameters()[0];
System.out.println("sorted type parameter: " + tv.getName()
+ " extends " + describe(tv.getBounds()[0]));
}
}The output is:
scores: Map<String, List<Integer>>
numbers returns: List<? extends Number>
numbers param: Set<String>
sorted returns: T[]
sorted param: List<T>
sorted type parameter: T extends Comparable<T>Two details are worth noting:
- A bare
?has the upper boundObject, so the code treatsObjectas "no bound". - A recursive bound such as
T extends Comparable<T>refers back toT. Describing the bound as a plain string, as above, avoids infinite recursion.
For simple printing you do not need a walker. Type.getTypeName() already returns a readable string such as java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>.
Capturing a type argument with a subclass
The Signature attribute also records the type arguments of a class's superclass. This gives a way to capture a type argument at runtime: declare an anonymous subclass. Libraries such as Gson and Jackson use this idea to support types like List<String>, which List.class cannot express.
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
abstract class TypeToken<T> {
final Type type;
protected TypeToken() {
Type superclass = getClass().getGenericSuperclass();
type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
}
}
public class TokenDemo {
public static void main(String[] args) {
Type t = new TypeToken<List<String>>() { }.type;
System.out.println(t);
}
}This prints java.util.List<java.lang.String>. The braces { } create an anonymous subclass of TypeToken<List<String>>. The compiler records that superclass declaration in the subclass's class file, and getGenericSuperclass() reads it back.
Without the braces, new TypeToken<List<String>>() creates a plain TypeToken. Its getGenericSuperclass() is Object.class, a Class and not a ParameterizedType, so the cast throws ClassCastException.
Common errors
- Casting
getGenericType()blindly. ForString namethe result is aClass, not aParameterizedType. Check withinstanceoffirst. - Expecting resolved type variables. In
class Box<T> { T value; }, the field's generic type is theTypeVariableT, even if you inspectBox<String>. Reflection does not substituteT. A subclassclass StringBox extends Box<String>lets you findStringthroughgetGenericSuperclass(), and you must map the variable yourself. - Forgetting arrays.
List<String>[]is aGenericArrayType.String[]is aClass. - Relying on
Class<T>alone.Class<List<String>>cannot be written as a literal, becauseList<String>.classdoes not exist. Use a type token or accept aType. - Generic creation. You cannot write
new T()ornew T[n], becauseTis not available at runtime. Pass aClass<T>or a factory as an argument.
Exercise
Given the field List<Integer> items; in a class Box, what do getType() and getGenericType() return for that field, and which of them can you use to find out that the list holds Integer?
Show answer
getType() returns List.class, the erased type, which has no argument information. getGenericType() returns a ParameterizedType whose getActualTypeArguments()[0] is Integer.class. Only the generic accessor can tell you the element type.
Exercise
A colleague writes List<String> names = new ArrayList<>(); and then tries to find out at runtime, from the names object alone, that it was meant to hold strings. Why is this impossible, and what could they inspect instead?
Show answer
Erasure removes the type argument from the object. names.getClass() is ArrayList whatever the declaration says. A local variable's declared type is not stored in the class file in a form reflection can read. If the list is held in a field or passed as a method parameter, they can read that declaration with getGenericType() or getGenericParameterTypes(). They can also capture the type with a TypeToken subclass.