Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm supposed to receive long integer in my web service.

long ipInt = (long) obj.get("ipInt");

When I test my program and put ipInt value = 2886872928, it give me success. However, when I test my program and put ipInt value = 167844168, it give me error :

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

The error is point to the above code.

FYI, my data is in JSON format :

{
    "uuID": "user001",
    "ipInt": 16744168,
    "latiTude": 0,
    "longiTude": 0,
}

Is there any suggestion so that I can ensure my code able to receive both ipInteger value?

like image 410
inayzi Avatar asked Sep 23 '19 06:09

inayzi


3 Answers

Both Integer and Long are subclasses of Number, so I suspect you can use:

long ipInt = ((Number) obj.get("ipInt")).longValue();

That should work whether the value returned by obj.get("ipInt") is an Integer reference or a Long reference. It has the downside that it will also silently continue if ipInt has been specified as a floating point number (e.g. "ipInt": 1.5) in the JSON, where you might want to throw an exception instead.

You could use instanceof instead to check for Long and Integer specifically, but it would be pretty ugly.

like image 99
Jon Skeet Avatar answered Nov 19 '22 11:11

Jon Skeet


We don't know what obj.get() returns so it's hard to say precisely, but when I use such methods that return Number subclasses, I find it safer to cast it to Number and call the appropriate xxxValue(), rather than letting the auto-unboxing throw the ClassCastException:

long ipInt = ((Number)obj.get("ipInt")).longValue();

That way, you're doing explicit unboxing to a long, and are able to cope with data that could include a ., which would return a Float or Double instead.

like image 23
Matthieu Avatar answered Nov 19 '22 11:11

Matthieu


Long.valueOf(jo.get("ipInt").toString());

Is ok.

like image 2
user13838991 Avatar answered Nov 19 '22 10:11

user13838991