Type erasure
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
explain what generics are at runtime and the consequences.
Planned topics
- Generic type arguments are checked at compile time, then erased; at runtime
List<String>is aList. - Consequences: no
new T(), noinstanceof List<String>, no generic arrays, no overloads differing only in type arguments. - The compiler inserts casts and generates bridge methods to keep overriding working.
- Heap pollution: raw types or unchecked casts let a wrong element enter a list; the failure appears later as
ClassCastException. - Workaround for runtime type info: pass a
Class<T>token.
Draft outline details
Demonstration
static <T> T create(Class<T> type) throws Exception {
return type.getDeclaredConstructor().newInstance(); // instead of new T()
}Check your understanding
Why does new T() not compile?
Show answer
T is erased; the JVM does not know the class at runtime.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.