πŸ”§ Error Fixes
Β· 1 min read

Java ClassCastException β€” How to Fix It


java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer

You’re trying to cast an object to a type it isn’t. Java’s type system caught the mismatch at runtime.

Fix 1: Check Type Before Casting

// ❌ Blind cast
Object obj = "hello";
Integer num = (Integer) obj;  // πŸ’₯

// βœ… Check with instanceof
if (obj instanceof Integer) {
    Integer num = (Integer) obj;
}

Fix 2: Generic Collection Without Type Safety

// ❌ Raw type β€” no compile-time checking
List items = new ArrayList();
items.add("hello");
Integer num = (Integer) items.get(0);  // πŸ’₯

// βœ… Use generics
List<String> items = new ArrayList<>();
items.add("hello");
String str = items.get(0);  // Type-safe

Fix 3: Deserialization Returns Wrong Type

// ❌ JSON/XML deserialized to unexpected type
Object result = objectMapper.readValue(json, Object.class);
MyClass obj = (MyClass) result;  // πŸ’₯ Might be a LinkedHashMap

// βœ… Deserialize to the correct type
MyClass obj = objectMapper.readValue(json, MyClass.class);

Fix 4: ClassLoader Conflict

// ❌ Same class loaded by different classloaders
// Common in web servers (Tomcat, Spring Boot with devtools)

// βœ… Check classloaders
System.out.println(obj.getClass().getClassLoader());
System.out.println(MyClass.class.getClassLoader());
// If different β†’ restart the server or fix classloader config

Fix 5: Use Generics Properly

// ❌ Casting from Object
Map<String, Object> map = getConfig();
String value = (String) map.get("count");  // πŸ’₯ Might be Integer

// βœ… Handle type safely
Object raw = map.get("count");
int count = raw instanceof Integer ? (Integer) raw : Integer.parseInt(raw.toString());