Scrivio Interview library
CodingIntermediate5 min read · updated 12 November 2026

Write a generic method <T> Page<T> readPage(String json, Class<T> itemType) that deserializes {"items": [...], "total": 3} into Page<T>. Why does a TypeReference not work here?

Inside a generic method, new TypeReference<Page<T>>() {} captures the type variable T itself, not the class the caller passed, because T has no concrete value at compile time; Jackson then treats the items as Object and builds maps. The fix is to build the type at runtime from the Class we receive: JavaType type = mapper.getTypeFactory().constructParametricType(Page.class, itemType), then mapper.readValue(json, type). Nested generics are built by composing JavaType objects, the type factory caches common types, and in Spring, ResolvableType.forClassWithGenerics gives the equivalent for ParameterizedTypeReference.

Why this question is asked

Generic helpers for paged responses are common in client libraries: one method reads any page of any item type. The natural first attempt uses TypeReference, compiles without warnings and returns a page of maps. Interviewers ask this question because it tests whether we understand what TypeReference really captures, a step beyond the basic List.class mistake. In this answer, we will set up the Page type, show why the TypeReference attempt fails, write the correct method with JavaType, handle nested generics and caching, and see the Spring equivalent.

1Setting Up the Page Type

We model the JSON {"items": [...], "total": 3} as a generic record. The item type is a parameter, so the same record serves orders, customers or anything else. We call it Page here; in a Spring Data project a different name avoids confusion with Spring Data's own Page interface.

Java
public record Page<T>(List<T> items, long total) {}
public record Customer(long id, String name) {}
String json = "{\"items\": [{\"id\":1,\"name\":\"Ann\"},{\"id\":2,\"name\":\"Bo\"},"
+ "{\"id\":3,\"name\":\"Cy\"}], \"total\": 3}";

2Why TypeReference Does Not Work Here

TypeReference works by capturing the type written in the source code of the anonymous subclass. In a call site such as new TypeReference<Page<Customer>>() {}, the source says Page<Customer>, so that is what gets recorded. Inside our generic method, the source says Page<T>. The compiler records exactly that: Page parameterized with the type variable T. The value of T for a particular call exists only in the caller's code and is erased; the anonymous class is compiled once and shared by all calls.

XML
<T> Page<T> readPageWrong(String json, Class<T> itemType) throws JsonProcessingException {
return mapper.readValue(json, new TypeReference<Page<T>>() {}); // captures Page<T>, not Page<Customer>
}
Page<Customer> page = readPageWrong(json, Customer.class);
System.out.println(page.total()); // 3
System.out.println(page.items().get(0)); // {id=1, name=Ann}: a LinkedHashMap
Customer c = page.items().get(0);
// ClassCastException: class java.util.LinkedHashMap cannot be cast to class Customer
Step throughWhat each approach hands to Jackson
readPageTypeReferenceTypeFactoryJackson
new TypeReference<Page<T>>() {}
Page<T>, T unresolved -> Object
items as LinkedHashMap
constructParametricType(Page.class, Customer.class)
Page<Customer> as JavaType
items as Customer

6 messages in order. Play them, or step through them one at a time.

Only the runtime Class carries the item type into a generic method.

When Jackson resolves Page<T>, it finds an unbound type variable and uses its bound, Object. So items becomes a list of maps, exactly as with List.class. Notice that the itemType parameter was never used: that unused parameter is the clue that the method cannot work.

3Building the Type at Runtime With JavaType

A JavaType is Jackson's own description of a full type, including generic arguments. Unlike a TypeReference, it can be built at runtime from Class objects. constructParametricType takes the raw generic class and the classes for its type parameters, in order.

XML
<T> Page<T> readPage(String json, Class<T> itemType) throws JsonProcessingException {
JavaType type = mapper.getTypeFactory().constructParametricType(Page.class, itemType);
return mapper.readValue(json, type);
}
Page<Customer> page = readPage(json, Customer.class);
System.out.println(page.items().get(0).getClass().getSimpleName()); // Customer
System.out.println(page.items().get(2).name()); // Cy
System.out.println(page.total()); // 3

Notice that now the itemType parameter does real work: it is the only way the method learns what T is, and it hands that knowledge to Jackson explicitly. Jackson resolves Page<Customer>, sees that the items component is a List<T> with T bound to Customer, and builds Customer objects.

4Nested Generics and Caching

When a type parameter is itself generic, for example a page of lists or a page of a generic wrapper, we compose JavaType objects: build the inner type first and pass it as the argument of the outer one. constructParametricType has an overload that takes JavaType arguments for exactly this.

Java
TypeFactory tf = mapper.getTypeFactory();
JavaType listOfCustomers = tf.constructCollectionType(List.class, Customer.class);
JavaType pageOfLists = tf.constructParametricType(Page.class, listOfCustomers); // Page<List<Customer>>
JavaType mapOfPages = tf.constructMapType(Map.class, tf.constructType(String.class),
tf.constructParametricType(Page.class, Customer.class)); // Map<String, Page<Customer>>

On caching: the TypeFactory already caches resolved types internally, so building a JavaType per call is cheap. On a very hot path we can still keep the JavaType in a field or a ConcurrentHashMap keyed by item class, since JavaType instances are immutable and safe to share. An ObjectReader built with mapper.readerFor(type) can be cached the same way and also skips looking up the deserializer on every call.

5The Spring Equivalent With ResolvableType

Spring's HTTP clients do not take a JavaType; they take a ParameterizedTypeReference. Writing new ParameterizedTypeReference<Page<T>>() {} inside a generic method fails for the same reason as TypeReference. Spring's ResolvableType solves it: forClassWithGenerics builds a parameterized type at runtime, and ParameterizedTypeReference.forType wraps it.

XML
<T> Page<T> fetchPage(String uri, Class<T> itemType) {
ResolvableType rt = ResolvableType.forClassWithGenerics(Page.class, itemType);
ParameterizedTypeReference<Page<T>> ref = ParameterizedTypeReference.forType(rt.getType());
return restClient.get().uri(uri).retrieve().body(ref); // Page<Customer> with Customer items
}
Which tool fits where
SituationToolWhy
Type fully known in the sourceTypeReference / ParameterizedTypeReferenceShortest, captured by the compiler
Item type known only at runtimeTypeFactory.constructParametricTypeBuilds the JavaType from Class objects
Same, through Spring HTTP clientsResolvableType.forClassWithGenericsWrap with ParameterizedTypeReference.forType
Type variable inside a generic methodNever TypeReference<...T...>Captures T itself, which resolves to Object

6Follow-up questions

Could readPage take a TypeReference parameter instead of a Class?

Yes, readPage(String json, TypeReference<Page<T>> type) works, because then the caller writes new TypeReference<Page<Customer>>() {} at the call site, where Customer is concrete. It moves the burden to every caller, so for a library API I prefer taking Class<T> and building the type inside, or offering both.

What happens if itemType is itself a generic class, such as List.class?

Then we are back to erasure at one level down: Page<List> with raw List items, whose elements become maps. For such cases the method should accept a JavaType or a TypeReference for the item type, so callers can describe the full nested type.

Does Jackson 3 change any of this?

The idea is the same: Jackson 3 still has TypeReference, JavaType and a TypeFactory, in the tools.jackson packages, and generic type variables still cannot be captured in a generic method. Check method names for your version if you port code.

7Conclusion

In this answer, we saw that new TypeReference<Page<T>>() {} inside a generic method captures the type variable T, which Jackson resolves to Object, so items became LinkedHashMaps. We built the type at runtime with constructParametricType(Page.class, itemType), composed JavaType objects for nested generics, cached types or readers on hot paths, and used ResolvableType.forClassWithGenerics with ParameterizedTypeReference.forType for Spring's HTTP clients.

What to say in the interviewAbout 80 seconds aloud

Open with

The method has to build the full type at runtime: JavaType type equals mapper.getTypeFactory().constructParametricType of Page.class and itemType, then return mapper.readValue of json and type. Jackson then knows it is reading a Page of, say, Customer, and builds Customer objects for the items.

Then, if they want more

A TypeReference does not work here because it captures the type written in the source of the anonymous subclass. Inside the generic method the source says Page of T, so that is literally what is recorded, the type variable T, not Customer. The anonymous class is compiled once for all calls, and the caller's actual type is erased.

Jackson resolves the unbound T to Object and the items become LinkedHashMaps, so we get a ClassCastException later. A good clue is that in the TypeReference version the itemType parameter is never used. For nested generics I compose JavaTypes, for example a collection type of Customer passed into the parametric type for Page.

The TypeFactory caches resolved types, and on hot paths I can also keep the JavaType or an ObjectReader in a field. In Spring, the same idea for RestClient or RestTemplate is ResolvableType.forClassWithGenerics of Page.class and itemType, wrapped with ParameterizedTypeReference.forType.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write a generic method <T> Page<T> readPage(String json, Class<T> itemType) that...": https://scrivio-interview-library.netlify.app/spring-boot/json-serialization/e323969eeb/