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;
}
}
}
您将会得到以下堆栈跟踪信息:
Exception in thread "main" java.lang.NullPointerException
at Foo.main(Foo.java:3)
为什么没有编译器警告或其他提示?在我看来,这是使用拆箱非常恶心的微妙之处,或者可能我太天真了。
补充@Javier提供的答案,如果您正在使用Eclipse,需要执行以下步骤以启用此功能:
- 导航到窗口 > 首选项 > Java > 编译器 > 错误/警告
- 展开潜在的编程问题
- 将装箱和拆箱转换切换为"警告"或"错误"
- 点击"确定"