I am accessing a MongoDB Java instance that is written in a Rails application. I am extracting integer values ββthat should be stored in Long, because they can exceed 32 bits.
This code will be compiled:
this.profile_uid = (Long)this.profile.get("uid");
However, I get an error during the type conversion:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
This is apparently because the field is returned by Mongo as Integer, but I know that some ID may appear as Longs, and for various reasons I can not change the type that was written to the database (from another application); it can be 32-bit in some cases and 64-bit in others.
The Java application should also handle, and I don't want to run any truncation or overflow problem. I want to read it as Long on the Java side.
I tried the workaround below and it seems to work, but I donβt know if I can be safe from truncation or overflow problems. I am not sure what the Number
class is in Java.
this.profile_uid = ((Number)this.profile.get("uid")).longValue();
It is legal? What side effects does he have? Is there another way?
source share