Video in progress

Strong Middle 🧱 OOP and SOLID

How can you keep a generic type at runtime? How does Jackson's `TypeReference` work?

Because of erasure, the Order in List<Order> doesn't exist at runtime. But generic information in a class declaration is kept: when you create the anonymous subclass new TypeReference<List<Order>>() {}, its supertype TypeReference<List<Order>> is written into the bytecode and can be read with reflection. This is the "super type token" pattern.

📖 Answer

The problem:

List<Order> orders = mapper.readValue(json, List.class);
// actually a List<LinkedHashMap>, not Order; ClassCastException later

You can't write List<Order>.class. The solution:

List<Order> orders = mapper.readValue(json, new TypeReference<List<Order>>() {});

The {} is an anonymous class. Here's what happens inside:

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

Generics in class, field and method signatures are stored in the bytecode in the Signature attribute: only the type inside an object instance is erased. The pattern relies on that.

Spring has the same thing: ParameterizedTypeReference:

List<Order> list = restClient.get().uri("/orders")
        .retrieve()
        .body(new ParameterizedTypeReference<List<Order>>() {});

The design takeaway: if your own generic API needs to know the type at runtime (deserialization, DI), ask for a Class<T> parameter (repo.find(Order.class)), or accept a type token for complex types. There is no other way to get T.class from a generic parameter.