Thursday, January 29, 2009

Java Auto-Boxing NullPointerException

What may one think to ones self, when a null pointer exception is thrown from a line of code as following:

MySpecialThing specialThing = new MySpecialThing (aLongArgument);

As if just to spite, the constructor is as harmless as:

MySpecialThing (long someNumber){ this.longNumber=someNumber;}

This is just one of those things that even an hours worth of code staring won’t resolve. The stack trace in this case gives no reasonable hint to what might be the problem. However, if its not obvious from the title, there is an auto-boxing of a Long object into a java primitive long.

The java compiler, wont see anything wrong, because such an assignment is perfectly legal, but at runtime if aLongArgument is delivered as null, the runtime exception is thrown from the constructor call(!).

Shameless.

1 comment:

  1. Autoboxing is one of the most useless and error-prone features in Java. In my company, we decided that usage of autoboxing is a compile error (this option exists in Eclipse) and are very happy.

    ReplyDelete

Please do not post spam on this blog, Spam sites will be reported to google.
thank you kindly.