Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long type cast error when reading Integer field from MongoDB in Java

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?

like image 976
Wolfram Arnold Avatar asked Jul 02 '12 02:07

Wolfram Arnold


2 Answers

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.

like image 196
Ian Daniel Avatar answered Oct 18 '22 16:10

Ian Daniel


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");
        }
    }
}
like image 39
mdewit Avatar answered Oct 18 '22 15:10

mdewit