Friday, February 24, 2012

An embarrassing NullPointerException

I did a classical mistake today, yet it took me long enough to find the error. I got a NullPointerException on the following method call (somewhat simplified):
myMethod(myObject.getId());
I was totally sure myObject was not null, and even though I knew that the id was null I didn't bother as that should not be a problem...until I checked the method signature of myMethod:
public void myMethod(long value) {...}
As it takes a primitive long as argument, and myObject's id was the object Long, an implicit conversion is made in the calling moment, so the real code looks like:
myMethod(myObject.getId().longValue());
I'm a fan of auto-boxing and -unboxing, but sometimes I obviously have to be a little more observant.

No comments:

Post a Comment