[英]Long type cast error when reading Integer field from MongoDB in Java
我正从Java中访问一个从Rails应用程序写入的MongoDB实例。 我正在检索应存储在Long中的整数值,因为它们可能超过32位。
这段代码将编译:
this.profile_uid = (Long)this.profile.get("uid");
但是,我收到类型转换运行时错误:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
这可能是因为Mongo将字段作为Integer返回,但是我知道一些ID可以作为Longs出现,并且由于各种原因我无法更改写入DB的类型(来自另一个应用程序); 在某些情况下它可能是32位而在其他情况下可能是64位。
Java应用程序需要处理任何一个,我不想遇到某种截断或溢出问题。 我想在Java端将其读作Long。
我已经尝试了下面的解决方法,它似乎运行,但我不知道我是否可以通过这种方式避免截断或溢出问题。 我不确定Java中的Number
类是做什么的。
this.profile_uid = ((Number)this.profile.get("uid")).longValue();
这是合法的吗? 它有什么副作用? 还有其他/更好的方法吗?
您建议的解决方法是合法的。 Number
是Java中所有数字类的超类。 如果您的"uid"
字段是数字格式,则this.profile.get("uid"))
将返回一个对象,该对象是Number
某个子类(因此转换为Number
将始终有效)。
Number
所有具体子类都必须实现longValue()
方法,因为它被定义为Number
类中的抽象方法。
Integer.longValue()
将其内部int值转换为long。 Long.longValue()
只返回其内部long值。
有时候不可能知道一个值是否是一个Long的整数。 我编写了这个类来轻松检索Long值。
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");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.