If you run the following code,
public class Foo{
public static void main(String[] args){
int id = new Bar().getId(); // throws unexpected NullPointerException
}
private static class Bar{
private final Integer id;
public Bar(){
this(null);
}
public Bar(Integer id){
this.id = id;
}
public Integer getId(){
return id;
}
}
}
you will get the following stacktrace,
Exception in thread "main" java.lang.NullPointerException
at Foo.main(Foo.java:3)
How come there's no compiler warning or anything? IMHO it's a pretty nasty subtlety with unboxing, or maybe I'm just naive.
Adding on to the answer provided by @Javier, if you're using Eclipse, you need to do the following to enable this:
I don't know what IDE are you using, but Eclipse has an option to enable warning on boxing and unboxing conversions. It is not possible to detect it as a null pointer access, since null is not immediatly unboxed, but via Bar.getId()
.
The expression of type Integer is unboxed into int
Foo.java line 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With