Video in progress

Senior ☕ Core Java

Even with erasure, how do Jackson's TypeReference<List<User>> or Spring's ParameterizedTypeReference know the generic type?

They create an anonymous subclass: new TypeReference<List<User>>() {}. The generic arguments of the superclass are stored in the Signature attribute of the .class file and are read with getGenericSuperclass(). Erasure removes the type from objects, not from class declarations.

📖 Answer

In an ordinary call, the information really isn't there:

List<User> users = mapper.readValue(json, List.class); // actually a List<LinkedHashMap>
users.get(0).getName();                                 // ClassCastException

List.class is a single class, and it says nothing about User. But the compiler keeps the generic information from the declarations of classes, fields and methods in the bytecode. The "super type token" trick relies on that:

abstract class TypeToken<T> {
    final Type type;
    protected TypeToken() {
        var sup = (ParameterizedType) getClass().getGenericSuperclass();
        this.type = sup.getActualTypeArguments()[0]; // List<User>
    }
}

Type t = new TypeToken<List<User>>() {}.type;   // {} makes an anonymous subclass

The {} declares a new class: class X$1 extends TypeToken<List<User>>. That declaration is written into the .class file, and reflection reads it. Jackson's TypeReference, Spring's ParameterizedTypeReference and Guava's TypeToken all use this mechanism.

List<User> users = restClient.get().uri("/users")
    .retrieve()
    .body(new ParameterizedTypeReference<List<User>>() {});

The traps:

  • forgetting the {}: since the constructor is protected/abstract, the compiler often stops you itself;
  • if you write new TypeReference<List<T>>() {} inside a generic method, what gets stored is T (a TypeVariable), not a concrete type. In a place like that, build the type dynamically: mapper.getTypeFactory().constructCollectionType(List.class, clazz), or in Spring ResolvableType.forClassWithGenerics(List.class, clazz);
  • creating a new anonymous object on every call is cheap, but on a hot path it's better to build the JavaType once and keep it in a static final.

The same information is present in field and method signatures (Field.getGenericType()), which is how Spring can inject the right beans into a field of type List<PaymentHandler>.