I'm accessing a MongoDB instance from Java that's written to from a Rails App. I'm retrieving integer values that should be stored in a Long, because they can exceed 32 bits.
This code will compile:
this.profile_uid = (Long)this.profile.get("uid");
However, I'm getting a type conversion run-time error:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
This is presumably because the field is returned by Mongo as Integer, but I know that some ID's can come as Longs and for various reasons I can't change the type that written to the DB (from another app); it may be 32-bit in some cases and 64-bit in others.
The Java app needs to handle either, and I don't want to run into some sort of truncation or overflow issue. I want to read it as a Long on the Java side.
I've tried the workaround below and it seems to run, but I don't know if I'm safe from truncation or overflow issues this way. I'm not sure what the Number
class in Java does.
this.profile_uid = ((Number)this.profile.get("uid")).longValue();
Is this legit? What side effects does it have? Is there another/better way?
Your suggested workaround is legitimate. Number
is the super-class of all number classes in Java. Provided that your "uid"
field is in a number format, this.profile.get("uid"))
will return an object which is some sub-class of Number
(and hence the cast to Number
will always work).
All concrete sub-classes of Number
must implement the longValue()
method, since it is defined as an abstract method in the Number
class.
Integer.longValue()
converts its internal int value to a long.
Long.longValue()
simply returns its internal long value.
It is sometimes impossible to know if a value would be an Integer of an Long. I have written this class to easily retrieve Long values.
public class MongoDbHelper {
public static Long getLongValue(Document doc, String key, Long defaultVal) {
Object obj = doc.get(key);
if (obj == null) {
return defaultVal;
} else if (obj instanceof Integer) {
return ((Integer) obj).longValue();
} else if (obj instanceof Long) {
return (Long)obj;
} else {
throw new ClassCastException("Could not convert " + obj.getClass() + " to Long");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With