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

查看:524
本文介绍了Java的简写形式当其中一个返回的对象为null时,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的简写形式当其中一个返回的对象为null时,If语句返回NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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