david david - 1 month ago 10
Java Question

How to convert object to long data type java

I have this code which gives me an error?

public int part(Object key) {
long clientId = (long) key;
...
}


Below is the error:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long


Not sure why it throws an exception.

Answer

As has been explained in the comments, Java does not allow casting of one primitive wrapper type into another type of primitive, even if the casting is allowed on the primitives themselves.

Your exception stacktrace is showing that the key parameter is an Integer object. If so, then simply use Integer's method created specifically for this type of conversion:

long clientId = ((Number) key).longValue();

You'd better be very sure that the key is always an Number object and is not null for this to work. You may need to test for null prior to this method being called.