Friday, January 8, 2010

Java autobox pitfall

I just wasted time figuring out a mysterious java.lang.NullPointerException thrown by a program I'm working on, because my Java coding standards result in my almost never getting a NullPointerException. I was calling a method that I didn't write (generated by JAXB that had the type signature

boolean isGood()

and assumed that this should have been a simple check of an attribute.

Looking at the generated code, I saw that it looked like


public boolean isGood() {
return good;
}


and was therefore puzzled, until I saw that good was not what I thought it was, a boolean, but rather

protected Boolean good;

Aha, autoboxing and unboxing! Of course, what was happening was that the Boolean instance variable good was uninitialized, and therefore null, and therefore the unboxing failed. This was unintuitive behavior to me, because it would be more sensible if for a Boolean, null were treated as converting to boolean value of false.

Or perhaps that way lies madness, and it's good that Java didn't turn into Perl with "smart" implicit conversions.

Anyway, what annoyed me was that just looking at the signature of boolean isGood(), I was misled. Clearly, JAXB should have generated Boolean getGood() instead, in order to make explicit the fact that it was handling a three-value variable instead of two.