Skip to content
Ameen Abozaid
Planned lessonMID-009-L01

Type erasure

  • Lesson 1 of 6
  • Mid-level
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 a List.
  • Consequences: no new T(), no instanceof 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

java
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.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.