取消装箱空盒装对象会引发意外的 NullPointerException [英] Unboxing a null boxed object throws unexpected NullPointerException

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

问题描述

如果你运行下面的代码,

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.

补充 @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天全站免登陆