Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. However I have found auto-unboxing to be confusing in some circumstances where the Number object may be null. Is there any way to detect where auto-unboxing is occurring in a codebase with a javac warning? 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.

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:

class Test {
    private Integer value;

    public int getValue() {
        return value;
    }
}
like image 280
Russ Hayward Avatar asked Jan 09 '10 13:01

Russ Hayward


2 Answers

Yup. In Eclipse:

Preferences->Java->Compiler->Errors/Warnings->Potential Programming Problems->Boxing and unboxing conversions

like image 176
skaffman Avatar answered Oct 05 '22 23:10

skaffman


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
  • Check for a null 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?

like image 29
Jeff Storey Avatar answered Oct 05 '22 22:10

Jeff Storey