NullPointerException from Boolean(来自布尔的 NullPointerException)
问题描述
这是我认为的 Java 纯粹主义者之一.我最近遇到了一个将字符串值自定义解析为布尔值的方法的问题.一个足够简单的任务,但由于某种原因,下面的方法在 null 情况下抛出 NullPointerException...
This is one for the java purists I think. I recently had an issue with a method to perform a custom parsing of String values to a Boolean. A simple enough task, but for some reason the method below was throwing a NullPointerException in the null case...
static Boolean parseBoolean(String s)
{
return ("1".equals(s) ? true : ("0".equals(s) ? false : null));
}
该方法的返回类型是布尔值,那么为什么或如何抛出 NullPointerException?从调试到似乎异常是在嵌套的内联条件语句计算为 null 并将 null 返回到外部内联条件的点引发的,但我再次无法解释原因.
The return type for the method is Boolean so why or how can a NullPointerException be thrown? From debugging through it seems the exception is being thrown at the point where the nested in-line conditional statement evaluates to null and returns null to the outer in-line conditional, but again I can't explain why.
最终我放弃了,改写了如下方法,效果符合预期:
Eventually I gave up and rewrote the method as follows, which works as expected:
static Boolean parseBoolean(String s)
{
if ("1".equals(s)) return true;
if ("0".equals(s)) return false;
return null;
}
以下代码介于两者之间,也可以按预期工作:
The following code is half way between the two and also works as expected:
static Boolean parseBoolean(String s)
{
if ("1".equals(s)) return true;
return "0".equals(s) ? false : null;
}
推荐答案
这也有效:
static Boolean parseBoolean(String s)
{
return ("1".equals(s) ? Boolean.TRUE : ("0".equals(s) ? Boolean.FALSE : null));
}
所以你得到 NPE 的原因是由于自动装箱,因为在三元运算符中使用 boolean
会导致表达式的结果被视为 boolean
.并且取消装箱 null
会导致 NPE.
So the reason you get an NPE is due to autoboxing because using boolean
in the ternary operator causes the result of the expression to be treated as a boolean
. And un-boxing of null
causes an NPE.
这篇关于来自布尔的 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:来自布尔的 NullPointerException
基础教程推荐
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01