简体   繁体   English

Java自动拆箱 - 是否有编译器警告?

[英]Java automatic unboxing - is there a compiler warning?

I am a big fan of auto-boxing in Java as it saves a lot of ugly boiler plate code. 我是Java中自动装箱的忠实粉丝,因为它节省了许多丑陋的锅炉板代码。 However I have found auto-unboxing to be confusing in some circumstances where the Number object may be null. 但是我发现自动拆箱在某些可能为null的情况下会引起混淆。 Is there any way to detect where auto-unboxing is occurring in a codebase with a javac warning? 有没有办法检测代码库中带有javac警告的自动拆箱位置? Any other solution to detect occurrences of unboxing only (such as FindBugs or Eclipse-specific compiler warning) would be appreciated as I cannot find any. 任何其他解决方案来检测仅出现拆箱(例如FindBugs或特定于Eclipse的编译器警告)将不胜感激,因为我找不到任何解决方案。

To clarify I do not want any warnings to be generated on boxing - only unboxing. 为了澄清我不希望在拳击上生成任何警告 - 仅取消装箱。

Here is a simple example of some code that can cause confusing NullPointerExceptions: 下面是一些可能导致混淆NullPointerExceptions的代码的简单示例:

class Test {
    private Integer value;

    public int getValue() {
        return value;
    }
}

Yup. 对。 In Eclipse: 在Eclipse中:

Preferences->Java->Compiler->Errors/Warnings->Potential Programming Problems->Boxing and unboxing conversions 首选项 - > Java->编译器 - >错误/警告 - >潜在的编程问题 - >装箱和拆箱转换

Unfortunately there is not. 不幸的是没有。 This is one of the issues with auto unboxing numbers. 这是自动取消装箱号码的问题之一。 You can 您可以

  • Initialize it to a default value, such as private Integer value = 0 将其初始化为默认值,例如private Integer value = 0
  • Check for a null return value != null ? value : 0 检查null return value != null ? value : 0 return value != null ? value : 0

Personally I prefer the first method. 我个人更喜欢第一种方法。 In general I would think you wouldn't have too many cases where you should have a null number. 一般来说,我认为你不会有太多你应该有空号的情况。

Also, why are you using a big Integer to store the value. 另外,为什么使用大整数来存储值。 If you're only returning a little int, why not store it that way? 如果你只是返回一点int,为什么不这样存储呢?

Eclipse will let you syntax-color boxing and unboxing operations (but not one or the other). Eclipse将允许您进行语法颜色装箱和拆箱操作(但不是一个或另一个)。 I have them set to bright red: if either happens, it means that I've been sloppy in matching parameters and arguments. 我把它们设置为鲜红色:如果发生任何一种情况,这意味着我在匹配参数和参数方面一直很邋。

I doubt that this will be a warning case. 我怀疑这是一个警告案例。 This is one of the quirks of auto-boxing. 这是自动拳击的怪癖之一。

Joshua Bloch addresses this in his book "Effective Java". Joshua Bloch在他的“Effective Java”一书中阐述了这一点。 Basically, the compiler is trying to do more for you that what is expected. 基本上,编译器正在尝试为您做更多的事情。 In other words, this type of issue is more commonly related to usage and as a result, it is difficult to "spot the error" as the error is, semantically speaking, simply not there. 换句话说,这种类型的问题通常与使用有关,因此,很难“发现错误”,因为从语义上讲,错误根本就不存在。

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

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