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());