当返回的对象之一为空时,Java If 语句的简短形式返回 NullPointerException [英] Short form for Java If statement returns NullPointerException when one of the returned objects is null

查看:14
本文介绍了当返回的对象之一为空时,Java If 语句的简短形式返回 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这段代码返回错误:java.lang.NullPointerException

Why this code returns the error: java.lang.NullPointerException

Object obj = null;
Long lNull = null;
Long res = obj == null ? lNull : 10L;

但是下面的方法没有任何错误:

But the following way works without any errors:

Object obj = null;
Long res = obj == null ? null : 10L;

推荐答案

在第二种情况下,编译器可以推断 null 必须是 Long 类型.在第一种情况下,它没有 - 并假设表达式返回 long.您可以看到情况就是这样(即修复它),例如

In the second case, the compiler can infer that the null must be a Long type. In the first case, it doesn't - and assumes that the expression returns a long. You can see that this is the case (i.e. fix it) like,

Long res = obj == null ? lNull : (Long) 10L;

不会产生 NullPointerException.

which does not yield a NullPointerException.

这篇关于当返回的对象之一为空时,Java If 语句的简短形式返回 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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