java 如何将对象转换为长数据类型java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40366858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:09:45  来源:igfitidea点击:

How to convert object to long data type java

javaobjectlong-integer

提问by john

I have this code which gives me an error?

我有这个代码,它给了我一个错误?

public int part(Object key) {   
    long clientId = (long) key;
    ...
}

Below is the error:

下面是错误:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

Not sure why it throws an exception.

不知道为什么会抛出异常。

回答by Hovercraft Full Of Eels

As has been explained in the comments, Java does not allow casting of one primitive wrapper type into another type of primitive, even if the casting is allowed on the primitives themselves.

正如评论中所解释的,Java 不允许将一种原始包装类型转换为另一种类型的原始类型,即使在原始类型本身上允许进行转换。

Your exception stacktrace is showing that the key parameter is an Integer object. If so, then simply use Integer's method created specifically for this type of conversion:

您的异常堆栈跟踪显示关键参数是一个 Integer 对象。如果是这样,那么只需使用专为此类转换创建的 Integer 方法:

long clientId = ((Number) key).longValue();

You'd better be very sure that the key is alwaysan Number object and is not null for this to work. You may need to test for null prior to this method being called.

您最好非常确定该键始终是一个 Number 对象并且不为 null 才能使其正常工作。您可能需要在调用此方法之前测试是否为 null。

回答by Justin L

You can't cast Integerto Long, even though you can convert from intto long. This would work for you:

您不能转换IntegerLong,即使您可以转换intlong。这对你有用:

Long clientId = new Long(key)

NPE is thrown if the Integer is null. I will leave the error handling up to you though. :)

如果 Integer 为空,则抛出 NPE。不过,我会将错误处理留给您。:)

Alternatively, you can use:

或者,您可以使用:

Long clientId = Long.valueOf(key.longValue());