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

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

本文介绍了如何将对象转换为长数据类型Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码给我一个错误吗?

I have this code which gives me an error?

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

以下是错误:

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

不确定为什么会引发异常.

Not sure why it throws an exception.

推荐答案

正如注释中所述,Java不允许将一种原始包装类型转换为另一种原始类型,即使在原始类型上允许进行转换也是如此.自己.

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.

您的异常stacktrace显示key参数是一个Integer对象.如果是这样,则只需使用专门为这种类型的转换创建的Integer方法:

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:

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

您最好确保键始终是 个Number对象,并且该键不能为null.在调用此方法之前,您可能需要测试null.

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

这篇关于如何将对象转换为长数据类型Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 22:27