来自布尔值的 NullPointerException

编程入门 行业动态 更新时间:2024-10-26 20:26:38
本文介绍了来自布尔值的 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)); }

该方法的返回类型是 Boolean 那么为什么或如何抛出 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

本文发布于:2023-11-05 15:46:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561240.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:布尔值   NullPointerException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!