[英]How to convert object to long data type java
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. 不知道为什么会引发异常。
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. 您的异常stacktrace显示key参数是一个Integer对象。 If so, then simply use Integer's method created specifically for this type of conversion:
如果是这样,则只需使用专门为这种类型的转换创建的Integer方法:
long clientId = ((Number) key).longValue();
You'd better be very sure that the key is always an Number object and is not null for this to work. 您最好非常确定该键始终是一个Number对象,并且不为null才能起作用。 You may need to test for null prior to this method being called.
在调用此方法之前,您可能需要测试null。
You can't cast Integer
to Long
, even though you can convert from int
to long
. 即使可以将
int
转换为Long
,也不能将Integer
转换为long
。 This would work for you: 这将为您工作:
Long clientId = new Long(key)
NPE is thrown if the Integer is null. 如果Integer为空,则抛出NPE。 I will leave the error handling up to you though.
不过,我会自行处理错误。 :)
:)
Alternatively, you can use: 或者,您可以使用:
Long clientId = Long.valueOf(key.longValue());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.