简体   繁体   English

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

[英]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.

相关问题 如何在Java中验证Long数据类型字段 - How to validate a Long data type field in java 无法将 java.lang.Long 类型的对象转换为类型(模型类) - Can't convert object of type java.lang.Long to type (modelclass) DatabaseException: 无法将 java.lang.Long 类型的对象转换为 (Model.class) 类型 - DatabaseException: Can't convert object of type java.lang.Long to type (Model.class) Java:如何将String转换为子类数据类型? - Java: How to convert a String into an subclass data type? 无法从类型对象转换为long - Cannot convert from type object to long Android / Java将String日期转换为long类型 - Android / Java convert String date to long type 如何在不将类型转换为其他对象的情况下直接将类型为Object的对象转换为Long - How to convert object of type Object to Long directly without typecasting it to other Object 如何将“unsigned long long int”转换为Java? - How to convert "unsigned long long int" into Java? 如何在 Java 中将 Object 类型转换为 int 类型? - How can I convert an Object type to a int type in Java? 获取错误:无法反序列化对象。 无法将 java.lang.String 类型的值转换为 long - Getting error : Could not deserialize object. Failed to convert a value of type java.lang.String to long
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM