为什么在这个方法调用中有一个 NullPointerException? [英] Why is there a NullPointerException in this method call?

查看:64
本文介绍了为什么在这个方法调用中有一个 NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我调用这样的方法时:

When I call a method like this:

int value1;
Integer value2 = null;

setValue(value2);

private void setValue(int value) {
    value1 = value;
}

为什么会出现 NullPointerException?

推荐答案

当前答案中没有提到的情况是形参类型是否为原始类型:

The case which hasn't been mentioned in the current answers is if the formal parameter type is primitive:

void setValue(int a) {
  // ...
}

这可以使用参数null 调用,因为编译器将尝试自动拆箱该值.有效:

This can be called with a parameter null, because the compiler will attempt to auto-unbox the value. Effectively:

setValue(null);

将被调用为:

setValue(((Integer) null).intValue());

但是,对于 NPE,这总是会失败,因为您不能取消引用空值.

However, this will always fail with NPE, because you can't dereference a null value.

但请注意,NPE 不会发生,因为 null 被传递给方法,而是因为将传递的值是如何计算的.区别很微妙,但很重要.

But note that the NPE doesn't occur because null is passed to the method, but rather because of how the value which would be passed is evaluated. The difference is subtle, but important.

任何值得使用的 IDE 都应将此标记为问题.

Any IDE worth using should flag this as a problem.

这篇关于为什么在这个方法调用中有一个 NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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