Dangerous auto(un)boxing
Today I've stumpled above a serious auto(un)boxing problem:
Number aNumber = aBooleanValue ? getIntegerObj() : getDoubleObj();
Method getIntegerObj returns an Integer, getDoubleObj a Double. Although aBooleanValue was true while debugging, aNumber contained a Double object after execution. The only explanation I had was an implicit autounboxing and immediat autoboxing. But what if the called get*Obj method returns null?
Even more strange, although autoboxing and autounboxing should be marked as warnings, nothing is marked.
Mike
Please sign in to leave a comment.
I fail to reproduce your example. No unboxing should be performed in this context.
Probably this is a bug in the compiler you are using?
Try out this class
public class Main {
// Static =================================================================
public static void main(String[] args) {
new Main(true).print();
}
// Fields =================================================================
private final boolean useInt;
// Setup ==================================================================
public Main(boolean useInt) {
this.useInt = useInt;
}
// Utils ==================================================================
private void print() {
final Number number = useInt ? getInteger() : getDouble();
System.out.println(number.getClass().getName());
}
private Integer getInteger() {
return new Integer(11);
}
private Double getDouble() {
return new Double(5.5);
}
}
with SUN's JDK 1.5.0_07.
Mike
Yep, the spec says about binary numeric promotion that may cause autounboxing...
... which also exposes a little bug in IDEA:
final Number number = useInt ? getInteger() : (Number)getDouble();
It thinks that the cast to Number is redundant... but it isn't. ;)
Maybe related to http://www.jetbrains.net/jira/browse/IDEA-3452 (just a guess as this also involves unboxing) ?
Fixed.
Hmm, does this forum have a built-in back-in-time device?
My Last Post -> Posted: Jul 5, 2006 11:57 AM
The one before -> Posted: Jul 5, 2006 12:02 PM
When is JB going to sell it? :)
Well, then this is another example of avoiding autounboxing where possible, because subtle bugs can be introduced.