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

When Raw Types Are Unavoidable

Rare legitimate cases for raw types, such as class literals and instanceof checks, where type parameters cannot be used.

When Raw Types Are Unavoidable

What you'll learn: Even though raw types are dangerous and discouraged, there are two specific situations where Java forces you to use them due to language limitations.

The Rare Exceptions to the "Never Use Raw Types" Rule

You've learned that raw types cause type safety loss and compiler warnings. However, Java's syntax has two corner cases where type parameters simply cannot be used, making raw types your only option.

Class Literals Must Use Raw Types

When you need to reference a class at runtime using .class, you must use the raw type. Java doesn't allow parameterized class literals.

Legal:

Class<?> listClass = List.class;  // Raw type required

Illegal:

Class<List<String>> c = List<String>.class;  // Won't compile!

Think of class literals as referring to the "blueprint" of the class itself, which exists before any type parameters are applied.

instanceof Checks Require Raw Types

Type parameters are erased at runtime, so instanceof cannot check parameterized types. You must use the raw type, then cast to the parameterized type if needed.

Correct pattern:

if (obj instanceof List) {  // Raw type required
    List<String> stringList = (List<String>) obj;  // Safe cast after check
}

Won't compile:

if (obj instanceof List<String>) {  // Illegal!

At runtime, a List<String> and List<Integer> are indistinguishable—both are just List. The instanceof operator works with runtime information only, where type parameters don't exist.

When to Use These Patterns

These are the only legitimate uses of raw types in modern Java. In both cases, you immediately restore type safety: with wildcards after the class literal check, or with a cast after instanceof.

Key Takeaway: Raw types are unavoidable only for class literals (List.class) and instanceof checks, where Java's type erasure makes parameterized types impossible; restore type safety immediately after these operations.