Long print error while reading Integer field from MongoDB in Java

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?

+6
source share
1 answer

Your recommended solution is legal. Number is the superclass of all classes of numbers in Java. If your "uid" field is in number format, this.profile.get("uid")) will return an object that is some subclass of Number (and therefore casting to Number will always work).

All concrete subclasses of Number must implement the longValue() method, since it is defined as an abstract method in the Number class.

Integer.longValue() converts the int int value to long. Long.longValue() simply returns its internal long value.

+5
source

Source: https://habr.com/ru/post/919465/


All Articles