Wednesday, May 28, 2008

Beware of hidden autoboxing features

Not so long ago I was asked on some interview - "Can you provide an example of an assignment operation, which causes a Runtime Exception". I started thinking about different casts, but couldn't find such example (though I passed the interview).
I haven't been working closely with Java 5 at those days. I heard and tried all those enums, generics, extended for and so on, but I haven't used this features in a real project.
Now I am involved in such Java 5 project, and recently I was fighting with some obscure exception, which unidentifiable cause and null stacktrace. It looked like this:
InvocationTargetException caused by NullPointerException: null. As all projects now, we are using all those proxies, CGLIB, interceptors etc, but anyway why no stacktrace??
Finally I found the reason. It was an autoboxing usage. The simplest possible example will look like this:

Boolean b = null;
//do something
boolean a = b;

The comparison operator will throw a NullPointerException. Looks very simple, if you already knew this; and if you run a search query "NullPointerException autoboxing" yuo find numerous results. But if you cannot link this NPE with that autoboxing usage, you can spend a day fighting with it, like I did.

No comments: