Course contentsShow
← Java
Lesson 896 of 2,87021. Generics FundamentalsFree lesson

No Generic Type Information at Runtime

Understanding that you cannot check instanceof with parameterized types or obtain generic type arguments via reflection at runtime.

No Generic Type Information at Runtime

What you'll learn: You'll understand why you cannot check types or retrieve generic parameters at runtime due to type erasure.


The Core Problem

Because of type erasure (which you just learned converts all type parameters to Object or their bound at compile time), Java completely discards generic type information before your program runs. This means at runtime, there's no difference between ArrayList<String> and ArrayList<Integer>—both are just ArrayList.

Think of it like shipping packages: the compiler checks labels carefully before shipping, but once the packages arrive (at runtime), all the detailed type labels have been removed. You only see "ArrayList," not "ArrayList containing Strings."

What You Cannot Do

Cannot use instanceof with parameterized types:

List<String> names = new ArrayList<>();

// ILLEGAL - won't compile
if (names instanceof List<String>) { }  // Error!

// LEGAL - only check the raw type
if (names instanceof List) { }  // OK

You can only check if something is a List, not what kind of elements it holds.

Cannot retrieve type arguments via reflection:

List<String> names = new ArrayList<>();
List<Integer> numbers = new ArrayList<>();

// Both print the same thing at runtime
System.out.println(names.getClass());    // class java.util.ArrayList
System.out.println(numbers.getClass());  // class java.util.ArrayList

// They are identical at runtime!
System.out.println(names.getClass() == numbers.getClass());  // true

The JVM sees both as plain ArrayList objects—the <String> and <Integer> parts vanished during compilation.


Key Takeaway:
Generic type parameters exist only at compile time; at runtime, all parameterized types become their raw equivalents, making instanceof checks and reflection-based type inspection impossible with generics.