Java automatic unboxing - is there a compiler warning?
-
19-09-2019 - |
Question
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;
}
}
Solution
Eclipse will let you syntax-color boxing and unboxing operations (but not one or the other). I have them set to bright red: if either happens, it means that I've been sloppy in matching parameters and arguments.
OTHER TIPS
Yup. In Eclipse:
Preferences->Java->Compiler->Errors/Warnings->Potential Programming Problems->Boxing and unboxing conversions
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?
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". 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.