打开一个空盒装对象会引发意外的NullPointerException异常 [英] Unboxing a null boxed object throws unexpected NullPointerException

查看:204
本文介绍了打开一个空盒装对象会引发意外的NullPointerException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您运行以下代码,

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)

怎么没有编译器警告或任何东西? IMHO这是一个非常讨厌的微妙与拆箱,或者也许我只是天真。

How come there's no compiler warning or anything? IMHO it's a pretty nasty subtlety with unboxing, or maybe I'm just naive.

添加 @ Javier ,如果您使用Eclipse,则需要执行以下操作来启用:

Adding on to the answer provided by @Javier, if you're using Eclipse, you need to do the following to enable this:


  1. 导航到窗口> 首选项> Java > 编译器> 错误/警告

  2. 展开潜在的编程问题

  3. 打包和取消分组转换切换为警告或错误

  4. 点击确定

  1. Navigate to Window > Preferences > Java > Compiler > Errors/Warnings
  2. Expand Potential programming problems
  3. Toggle Boxing and unboxing conversions to either "Warning", or "Error"
  4. Tap "OK"


推荐答案

我不知道你在使用什么IDE,但是Eclipse可以选择启用打包和取消分组转换的警告。不可能将其检测为空指针访问,因为null不是立即取消装箱,而是通过 Bar.getId()

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().


类型为Integer的表达式被取消装箱到int

Foo.java第3行

The expression of type Integer is unboxed into int
Foo.java line 3

这篇关于打开一个空盒装对象会引发意外的NullPointerException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆