How to Fix ClassCastException "java.lang.Integer cannot be cast to class java.lang.Long"


Trying to cast an Object may throw a ClassCastException.

Object obj = 1;
long longVal = (long) obj;

The error stack trace will look something like this:

java.lang.ClassCastException: class java.lang.Integer cannot be cast to class 
java.lang.Long (java.lang.Integer and java.lang.Long are in module java.base 
of loader 'bootstrap')

The same error can be found with any pair of types: java.lang.Double cannot be cast to java.lang.Integer.

1. Using Number casts

When it comes to handling Number subclasses (e.g. Integer, Long), we don’t need to rely on the auto-unboxing (i.e. the automatic conversion between the primitive types and their corresponding object wrapper classes).

It’s safe to cast the value to Number and call the appropriate method to obtain the value (e.g. intValue(), longValue()).

Object obj = 1;
long longVal = ((Number) obj).longValue();

Similarly:

Object obj = 1L;
int intVal = ((Number) obj).intValue();

The downside to this solution is that it will silently continue if obj is a floating point number or double, a scenario in which we’d prefer an exception to be thrown.

2. Using instanceof

We can also just use instanceOf to check for the appropriate type.

Object obj = 1;
if (obj instanceof Integer) {
  int intVal = ((Integer) obj).intValue();
} else if (obj instanceof Long) {
  long longVal = ((Long) obj).longValue();
}

3. Using toString()

We can also cast to a String and pass it into valueOf().

Object obj = 1;
long longVal = Long.valueOf(obj.toString());