Video in progress
What is type erasure in generics, and what limitations does it bring?
Generic type parameters exist only at compile time; in the bytecode they're erased (List<String> becomes List). So at runtime there's no information about T: you can't do new T(), instanceof List<String>, or create a T[].
📖 Answer
List<String> a = new ArrayList<>();
List<Integer> b = new ArrayList<>();
a.getClass() == b.getClass(); // true: both are ArrayList
The compiler does the type checking and inserts the needed casts itself. At runtime, a List works only with Objects.
The limitations:
class Box<T> {
T create() { return new T(); } // error
boolean is(Object o) { return o instanceof T; } // error
T[] arr = new T[10]; // error
}
void process(List<String> s) {}
void process(List<Integer> i) {} // error: the same signature after erasure
The way around it is to pass a Class<T> explicitly:
<T> T fromJson(String json, Class<T> type) { ... }
For a generic type (for example, List<User>), Jackson uses TypeReference and Spring uses ParameterizedTypeReference: they keep the type through an anonymous subclass.
The lack of primitive generics (List<int>) is mostly a result of this same design.
Sign up to mark studied questions and save your progress.