Sub topic 12
Generic type information and type erasure
This chapter assumes you know generics and collections, and that you can already get a Class object and read a Field from it. It covers what generic information survives at runtime and how to read it.
What erasure removes
The compiler checks generic types and then erases them. At runtime, a List<String> object is just a List. The object does not know its element type.
import java.util.ArrayList;
import java.util.List;
public class ErasureDemo {
public static void main(String[] args) {
List<String> a = new ArrayList<>();
List<Integer> b = new ArrayList<>();
System.out.println(a.getClass() == b.getClass());
}
}This prints true. Both lists share the class ArrayList. No reflection call on the object can tell you the element type.
What survives in declarations
The compiler still writes generic signatures into the class file. They appear on field types, method parameter types, return types, and superclasses. Reflection can read them. They are not available for the type arguments of an object created with new.
| You ask | Result for a field `List<String> names` |
|---|---|
| `field.getType()` | `interface java.util.List` (erased) |
| `field.getGenericType()` | `java.util.List<java.lang.String>` |
Reading a parameterized field type
getGenericType() returns a Type. When the declaration has type arguments, that Type is a ParameterizedType.
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]);
}
}
}The output is interface java.util.List followed by class java.lang.String. getRawType() gives the erased type. getActualTypeArguments() returns an array, one entry per type argument.
The Type hierarchy
Type is a small interface with several subtypes. Check which one you have before casting.
| Subtype | Represents | Example |
|---|---|---|
| `Class` | A plain type | `String` |
| `ParameterizedType` | A type with arguments | `List<String>` |
| `TypeVariable` | A declared type parameter | `T` |
| `WildcardType` | A wildcard | `? extends Number` |
| `GenericArrayType` | An array of a generic type | `List<String>[]` |
Type arguments can themselves be parameterized. For Map<String, List<Integer>>, the second argument is a ParameterizedType, so you may need to recurse.
Where this is used
Frameworks use this to learn what a declaration expects. A JSON library can read List<Person> from a field and decide to build Person objects for each element. A dependency injection container can do the same for a constructor parameter.
The same idea works on classes. If class NameList extends ArrayList<String>, then NameList.class.getGenericSuperclass() returns ArrayList<String>, because the superclass declaration is stored in the class file. Libraries use this trick to capture a type argument by creating an anonymous subclass.
Exercise
Given class Box { java.util.Map<String, Integer> data; }, how do you print the type of the map's values using reflection, and why can't you get the same answer from a Map object stored in that field?
Show answer
Get the field with Box.class.getDeclaredField("data"), call getGenericType(), cast to ParameterizedType after an instanceof check, and print getActualTypeArguments()[1], which is class java.lang.Integer. The object stored in the field is erased: its class is just something like HashMap, and the type arguments exist only in the field's declaration in the class file.