简体   繁体   English

用Java将int转换为long

[英]Cast int to long in Java

This questions has many answers and I have seen them. 这个问题有很多答案,我已经看到了。 I have code that has been working but today suddenly it starting throwing java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long for the line 我有一直在工作的代码,但今天突然它开始抛出java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

return null == input.get(keyName) ? 0L : (long) input.get(keyName);

Error is coming from (long) input.get(keyName) . 错误来自(long) input.get(keyName) I wonder why it starting breaking all of sudden. 我不知道为什么它突然开始崩溃。 (long) input.get(keyName) this looks good to me. (long) input.get(keyName)这对我来说很好。 I thought of doing ((Integer) input.get(keyName)).longValue() but was getting java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer as map sometimes contains long values. 我想做((Integer) input.get(keyName)).longValue()但正在获取java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer因为地图有时包含long值。 Any suggestions 有什么建议么

Stacktrace: 堆栈跟踪:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
    at accountservice.adapter.batch.testJob.SyncDriverPartitioner.getLongValueFromMap(SyncDriverPartitioner.java:78) ~[classes/:?]
    at accountservice.adapter.batch.testJob.SyncDriverPartitioner.partition(SyncDriverPartitioner.java:47) ~[classes/:?]
    at accountservice.adapter.batch.testJob.SyncDriverPartitioner$$FastClassBySpringCGLIB$$6f3315e4.invoke(<generated>) ~[classes/:?]
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.18.RELEASE.jar:4.3.18.RELEASE]

You can take advantage of the fact that all numeric primitive wrappers extend java.lang.Number : 您可以利用所有数字原始包装器都扩展java.lang.Number的事实:

return null == input.get(keyName) ? 0L : ((Number) input.get(keyName)).longValue();

As to why it started giving errors suddenly; 关于为什么突然开始出现错误; really the only likely reason is that up until it started failing, you were always putting java.lang.Long objects in the input Map, and it changed so you're also putting java.lang.Integer in them now. 真的是唯一可能的原因是,直到它开始失败,你总是把java.lang.Long的对象input地图,它改变所以你也把java.lang.Integer在其中了。

It's quite easy for that to happen with auto-boxing and numeric constants: 使用自动装箱和数字常量很容易做到这一点:

long v = 42;
input.put("key", v);  // Puts a java.lang.Long in the map
input.put("key", 42); // Puts a java.lang.Integer in the map
input.put("key", 42L); // Puts a java.lang.Long in the map

You can avoid it by declare your Map type-safely ( Map<String, Long> ). 您可以通过安全地声明Map类型( Map<String, Long> )来避免这种情况。 If you do that, input.put("key", 42) will give a compile-time error. 如果这样做, input.put("key", 42)将给出编译时错误。

Rather than casting an int to a long I would suggest: 我建议不要将int转换为很长的整数:

return null == input.get(keyName) ? 0L : Integer.toUnsignedLong(input.get(keyName))

At least this way you should get some more information about why it cannot be converted to a long rather than just a ClassCastException 至少通过这种方式,您应该获得有关为何不能将其转换为long而不是ClassCastException的更多信息。

Answer Update 答案更新

Based on your comments I guess you are going to have to check type of the entry in Map before processing it, I would suggest the following: 根据您的评论,我想您将不得不在处理之前检查Map中条目的类型,我建议以下内容:

    Object keyValue = input.get(keyName);
    if (null == keyValue) return 0L;
    String valueType = keyValue.getClass().getTypeName();
    if (valueType.equals(Long.class.getTypeName())) {
        return (long) keyValue;
    }
    if (valueType.equals(Integer.class.getTypeName())) {
        return Integer.toUnsignedLong((int) keyValue);
    }
    throw new TypeMismatchException(String.format("Type '%s' is not supported...", valueType));

This will let you define different operations for different types of entry, it is extendable to any types you want to support. 这将使您可以为不同类型的条目定义不同的操作,并且可以扩展到要支持的任何类型。 You can tweak the exception thrown as well to provide you relevant information. 您还可以调整抛出的异常,以向您提供相关信息。

The snippet above shows you the actual type so that you can extend your code to support that type, or work out why something of that type got into your map. 上面的代码段向您显示了实际的类型,以便您可以扩展代码以支持该类型,或者确定为什么这种类型的内容进入了地图。

It should be noted that it would probably be better to do this when data is entered into the map, not when it's taken out of the map. 应该注意的是,将数据输入地图时最好这样做,而不是从地图中取出时。 In which case you should be able to change your map to a type . 在这种情况下,您应该可以将地图更改为type。 It's always better to sanitise your imputes than trying to deal with a mishmash of mixed data types at a later date. 与以后处理杂乱的数据类型相比,清理归因总是更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM