Skip to content
javahacks.dev
Java Core

Fix ClassCastException and Heap Pollution in Java Code

Why ClassCastException appears where no cast is written, how raw types and unchecked warnings cause heap pollution, and how to fix it at the source.

7 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the OpenJDK, Spring, Apache Maven and JUnit5 logos.

A List<String> that contains an Integer should be impossible, since the compiler checks every add. Yet a loop over the list dies with ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String, on a line with no cast in it. The explanation is that Java generics are a compile-time check that is erased before the program runs, so the guarantee holds only if every piece of code that touches the list played by the rules. When one does not, the wrong object sits quietly inside the collection until something reads it, which can be far from the cause. That condition is called heap pollution, and the exception is where it finally shows. This post reproduces it with real output, lists how pollution starts, fixes the insertion rather than the symptom, handles the casts you wrote yourself and explains the version of the error that has two class loaders in it. Output below comes from running the code on JDK 17; the behavior is the same on JDK 25.

How a list of strings holds an integer

The smallest reproduction uses a raw type, which the compiler allows with a warning:

src/main/java/dev/javahacks/generics/Pollution.javajava
import java.util.ArrayList;
import java.util.List;

public class Pollution {

    @SuppressWarnings({"unchecked", "rawtypes"})
    static void addRaw(List list, Object o) {
        list.add(o);                       // the compiler cannot check this
    }

    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        addRaw(names, 42);
        System.out.println(names.size());

        for (String n : names) {           // the failing line has no visible cast
            System.out.println(n.length());
        }
    }
}
Text
1
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')

Line one shows the list accepted the integer and reports a size of 1, because at runtime it is just a list of Object. The exception comes later, in the loop. The compiler inserted an invisible cast to String where the loop reads the element, because it trusted the declared type. That cast is where the bad object is caught, and it is the reason the stack trace points at an innocent line. The distance between the polluting call and the failing read can be one line or one week of uptime and three services.

The compiler does warn when this can happen. The messages unchecked call to add(E) as a member of the raw type List and unchecked cast are the early notice. Treat them as errors with -Xlint:unchecked -Werror, or at least read them.

Common ways pollution starts

Raw types. The example above. A method that takes a bare List or Map discards all type information, and an old library API that returns raw types hands you a collection you cannot trust.

Unchecked casts. Converting Object to List<String> with (List<String>) obj is checked only as far as List; the element type is a promise you made. Deserialization, reflection and framework APIs that return Object produce these.

Generic varargs. A method taking List<String>... creates an array of a generic type, which is unsafe. The array is covariant, so it can be viewed as Object[] and filled with anything:

java
static void dangerous(List<String>... lists) {
    Object[] arr = lists;
    arr[0] = List.of(42);          // stores a List<Integer> where List<String> was promised
    String s = lists[0].get(0);    // ClassCastException here
}
Text
class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')

@SafeVarargs suppresses the warning for a method you have checked does not write into the array; applying it to a method that does is the same bug with the alarm turned off.

Generic arrays. A helper like toArray(T... xs) that returns its varargs array is the classic. The array's runtime type is the erasure of T, which is Object[], not String[], so assigning it to a String[] fails at the call site:

java
@SafeVarargs
static <T> T[] toArray(T... xs) { return xs; }
static <T> T[] pick(T a, T b) { return toArray(a, b); }

String[] a = pick("a", "b");      // ClassCastException on this line
Text
class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.String; ([Ljava.lang.Object; and [Ljava.lang.String; are in module java.base of loader 'bootstrap')

Notice the [L prefix: it is the JVM's name for an array type. Fix it by taking an array factory (IntFunction<T[]>) or a Class<T>, or by returning a List<T>, which has no such trap.

Fix the insertion

Chasing the failing read is the wrong end. The bug is the line that put the wrong object in. To find it without guessing, wrap the collection in a checked view while you debug:

java
List<String> names = Collections.checkedList(new ArrayList<>(), String.class);
addRaw(names, 42);
Text
Attempt to insert class java.lang.Integer element into collection with element type class java.lang.String

A checked collection verifies the type on every add, so the exception is thrown at the polluting call, and its stack trace names the culprit. Collections.checkedMap, checkedSet and the others work the same way. Add the wrapper temporarily in a test or a debug build; the checks cost a little on each insertion.

Once found, the fix is usually to remove the raw type or the unchecked cast. Give the method a real signature:

java
static <T> void add(List<T> list, T element) {
    list.add(element);
}

add(names, 42);        // now a compile error: incompatible types

A compile error is the best outcome, because it moves the failure from production to your editor. If a library forces a raw type on you, confine it: convert at the boundary into a typed collection by copying and checking each element, and leave nothing raw beyond that line.

java
static List<String> strings(List<?> source) {
    List<String> out = new ArrayList<>(source.size());
    for (Object o : source) {
        out.add((String) o);         // fails here, with the bad element in hand
    }
    return out;
}

Casts you did write

Not every ClassCastException involves generics. An explicit cast to a type the object does not have fails with a precise message:

java
Object o = "text";
Integer i = (Integer) o;
Text
class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')

The common real-world version is a heterogeneous map, such as parsed JSON or a framework attribute bag, where a number arrives as a different type than you assumed:

java
Map<String, Object> m = new HashMap<>();
m.put("n", 1L);
Integer n = (Integer) m.get("n");      // the value is a Long
Text
class java.lang.Long cannot be cast to class java.lang.Integer (java.lang.Long and java.lang.Integer are in module java.base of loader 'bootstrap')

Do not cast between number wrappers; ask the value to convert itself: ((Number) m.get("n")).intValue(). For anything with several possible types, use a pattern match, which cannot throw:

java
Object v = m.get("n");
String shown = switch (v) {
    case Integer i -> "int " + i;
    case Long l    -> "long " + l;
    case String s  -> "text " + s;
    case null      -> "absent";
    default        -> "other " + v.getClass().getName();
};

The language features that make this tidy are covered in the modern Java guide. Guard an unavoidable cast with instanceof first, or use Class.cast, which gives a better message and works with a Class<T> token.

The two-classloaders case

The message that confuses people most reads as if a class were cast to itself:

Text
java.lang.ClassCastException: class com.acme.Plugin cannot be cast to class com.acme.Plugin (com.acme.Plugin is in unnamed module of loader 'app'; com.acme.Plugin is in unnamed module of loader com.acme.PluginLoader @4e50df2e)

It is not a typo. The JVM identifies a class by its name and the class loader that defined it. Load com.acme.Plugin through two loaders and you have two unrelated types that share a name. This happens with plugin systems, application servers, hot reload (Spring DevTools uses a restart loader on purpose) and OSGi. Read the parenthesized part: it names both loaders. The fix is structural: the shared interface must be loaded by a common parent loader, so both sides see the same class, and only the implementations come from the child. The debugging method for finding which jar supplied which copy is in debugging classpath and class loading problems.

Where this does not apply

If the cast is inside generated or proxied code (a name like $$SpringCGLIB$$ or $Proxy12), the cause is often that a JDK proxy implements the interface but not the concrete class you cast to; inject the interface type instead. If the exception is thrown from a framework's JSON or ORM mapping, the data does not match the declared type, and the fix is in the schema or the mapper. To trace where an exception was really thrown, see reading a Java stack trace correctly. The exception's contract is in the Javadoc, and the tutorial on why some varargs are unsafe is in the Java generics tutorial.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.