为什么在这个方法调用中有一个 NullPointerException?

尼尔斯

当我调用这样的方法时:

int value1;
Integer value2 = null;

setValue(value2);

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

为什么有一个NullPointerException

安迪·特纳

当前答案中未提及的情况是形参类型是否为原始类型:

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

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

setValue(null);

将被调用为:

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

但是,对于 NPE,这将始终失败,因为您无法取消引用空值。

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么没有一个NullPointerException并运行一个空对象上调用此方法?

Scala中有一个奇怪的NullPointerException

为什么在这个解散的 std::string dtor 中有一个锁定的 xadd 指令?

为什么在这里得到NullPointerException?

JUnit调用一个方法并调用另一个方法将返回nullPointerException

为什么在我的排序实现中有NullPointerException?

为什么这个简单的代码抛出NullPointerException?

NullPointerException为什么?

NullPointerException-为什么?

为什么这个答案中有一个 en?

为什么在调用notifyDataSetChanged时发生NullPointerException?

为什么不能调用getFont()方法并给出NullPointerException。

NullPointerException用于调用另一个类数组

NullPointerException在getSystemServiceName(...)调用上

为什么@PostConstruct导致NullPointerException?

为什么模拟抛出nullpointerexception?

为什么会出现NullPointerException?

为什么会出现nullpointerexception?

getCurrentSession()-NullPointerException-为什么?

为什么JDA返回NullPointerException?

在与请求对象关联的空对象上调用方法时,JSTL中没有NullPointerException。为什么?

为什么此WAV文件无法播放?它给了我一个NullPointerException

如果findFirst()找到的第一个元素为null,为什么会抛出NullPointerException?

为什么 WebElement.isDisplayed() 给我一个 NullPointerException

带有 HikariCP 的 NullPointerException

带有JDatePicker的NullPointerException

带有NullPointerException的列表

具有JacocoPluginExtension的NullPointerException

在这个链表中,为什么它不允许我再次运行并创建另一个节点,我的代码中有什么错误?