Quick revision
The short answer
We replace Object find(String type, Object id) with a generic interface, interface Repository<T, ID> { Optional<T> findById(ID id); List<T> findAll(); T save(T entity); }, the shape Spring Data uses, so each repository is typed and callers need no casts. When the type is only known at run time, we pass a Class<T> token, as in <T> T find(Class<T> type, Object id), and use type.cast. For generic result types such as List<Order>, a Class token is not enough, so we use a type token such as Jackson's TypeReference or Spring's ParameterizedTypeReference. And we keep signatures simple, because too many type parameters make an API hard to use.
What to remember
In this answer, we replaced an untyped find(String, Object) with a generic Repository<T, ID> in the style of Spring Data, which removes casts and turns wrong types and ids into compile errors. For types known only at run time, we passed a Class<T> token and used type.cast, and for parameterized types such as List<Order>, we used a type token such as TypeReference or ParameterizedTypeReference, which survives erasure through an anonymous subclass. We also kept the number of type parameters small so the API stays readable.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We replace Object find(String type, Object id) with a generic interface, interface Repository<T, ID> { Optional<T> findById(ID id); List<T> findAll(); T save(T entity); }, the shape Spring Data uses, so each repository is typed and callers need no casts. When the type is only known at run time, we pass a Class<T> token, as in <T> T find(Class<T> type, Object id), and use type.cast. For generic result types such as List<Order>, a Class token is not enough, so we use a type token such as Jackson's TypeReference or Spring's ParameterizedTypeReference. And we keep signatures simple, because too many type parameters make an API hard to use.
Why this question is asked
An untyped repository layer is a common sight in older codebases: one method that takes a type name as a string, returns Object, and leaves every caller to cast. Each cast is a small bet that the string and the cast agree, and a wrong bet becomes a ClassCastException in production. Interviewers ask this design question to see whether we can apply generics to a real API, including the awkward cases where types are only known at run time. In this answer, we will look at what is wrong with the current design, build the typed interface, handle run-time types with class tokens, handle generic types with type tokens, and discuss when generality goes too far.
1What Is Wrong With the Untyped Design
Here is the current code and a typical caller.
The compiler cannot help at all. The string "order" and the cast to Order are two separate claims, and nothing checks that they agree. The id is an Object, so passing a String where a Long is expected also compiles. Every one of these mistakes becomes a run-time failure, and the casts spread through the codebase, making refactoring risky. The goal of the redesign is to let the compiler check what the strings and casts used to promise.
2Building a Typed Repository Interface
Generics let the interface carry two type parameters: T, the entity type, and ID, the type of its identifier. Each concrete repository fills them in once, and every method is then typed.
| Mistake | Object find(String, Object) | Repository<T, ID> |
|---|---|---|
| Wrong cast on the result | ClassCastException at run time | compile error |
| Typo in the type name | run-time failure | impossible: no names |
| Wrong id type | run-time failure or wrong row | compile error |
| Not found | null, easy to forget | Optional<T> in the signature |
This is exactly the shape of Spring Data's CrudRepository<T, ID>, which is no accident: the problem is universal. Notice the use of Optional<T> rather than a nullable T, which makes the not-found case part of the type. The errors that were run-time ClassCastExceptions are now compile errors at the call site, and the string type names are gone entirely, because the repository type itself says what it holds.
3When the Type Is Chosen at Run Time: Class Tokens
Some code really does not know the type until run time, such as a generic admin screen that loads any entity by name, or a message handler that reads the type from a header. For those cases we pass a Class<T> object, called a class token, instead of a string. The token is both a run-time value and a compile-time type.
Notice that Class<T> links the two worlds. At compile time, passing Order.class makes T equal to Order, so the result needs no cast. At run time, type.cast(raw) checks that the object really is an Order, so a mismatch fails at this one line, inside the repository, rather than somewhere in the caller. This is the same technique as JPA's EntityManager.find(Class<T>, Object).
4When the Type Is Itself Generic: Type Tokens
Class tokens stop working for parameterized types. There is no List<Order>.class, because of erasure: at run time there is only one List class, and List<Order> and List<Customer> are the same. If our repository loads a list of orders from JSON, a Class token cannot express the element type.
- Is the type known at compile time?YesUse a typed repository: Repository<Order, Long>NoContinue
- Is the run-time type a plain class?YesPass Class<T> and use type.castNoContinue
- Pass a type token
TypeReferenceorParameterizedTypeReference
3 steps in order. Play them, or step through them one at a time.
The trick in both is the anonymous subclass, the {} at the end. When we create an anonymous subclass of TypeReference<List<Order>>, the compiler records List<Order> as the generic supertype of that subclass in the class file, and that information survives erasure. The library reads it with reflection, through getGenericSuperclass(), and knows the full type. This is called a super type token. Our own API can accept such a token wherever callers need to ask for a generic type.
5Not Going Too Far
Generics can be overdone. A signature such as <T extends Entity<ID>, ID extends Comparable<ID>, R extends Repository<T, ID>, Q extends Query<T>> is technically precise and practically unreadable; error messages become pages long, and callers stop understanding what they are allowed to pass. Two type parameters, T and ID, cover nearly every repository need. Extra parameters should earn their place by removing real casts or real bugs, not by expressing every theoretical relationship. A good test is whether a new team member can call the method correctly without reading its declaration twice.
6Follow-up questions
How do we migrate callers from the old method without a big-bang change?
Add the typed repositories alongside the old method, implement them by delegating to the existing code, and mark find(String, Object) as @Deprecated. Then move callers module by module, which removes their casts, and delete the old method when nothing uses it. Compiler deprecation warnings show what is left.
Why does TypeReference need the curly braces?
Without them we would be creating an instance of TypeReference itself, whose type argument is erased. The braces create an anonymous subclass, and a subclass's generic superclass, including its type arguments, is stored in the class file and can be read with reflection.
Is type.cast different from a normal cast?
It does the same check, but it works with a Class object at run time, so it can be used where the type is a type parameter T. A plain (T) cast on a type parameter is unchecked and does nothing at run time, which would let a wrong object escape.
7Conclusion
In this answer, we replaced an untyped find(String, Object) with a generic Repository<T, ID> in the style of Spring Data, which removes casts and turns wrong types and ids into compile errors. For types known only at run time, we passed a Class<T> token and used type.cast, and for parameterized types such as List<Order>, we used a type token such as TypeReference or ParameterizedTypeReference, which survives erasure through an anonymous subclass. We also kept the number of type parameters small so the API stays readable.
Open with
I would replace it with a generic interface like Spring Data's: interface Repository<T, ID> with Optional<T> findById(ID id), List<T> findAll() and T save(T entity), and then concrete interfaces such as OrderRepository extends Repository<Order, Long>.
Then, if they want more
Callers then get compile-time types: no casts, a wrong id type is a compile error, and the string type names disappear. Optional also makes not-found explicit.
For the places where the type really is only known at run time, I would pass a class token instead of a string: <T> T find(Class<T> type, Object id), and inside use type.cast, which gives the caller a typed result and fails with a clear error at one place if the object is wrong.
That is the same approach as EntityManager.find. A Class token is not enough for generic types like List<Order>, because there is no List<Order>.class after erasure, so for those I would accept a type token, like Jackson's TypeReference or Spring's ParameterizedTypeReference, which use an anonymous subclass so the full generic type is kept in the class file.
The trade-off I would watch is over-generalising: two type parameters cover almost everything, and signatures with four or five bounded parameters make the API harder to use than the casts they replace.
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.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
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 "Your team's repository layer has methods like Object find(String type, Object id) with...": https://scrivio-interview-library.netlify.app/java/generics/c62e9c9eb7/