Java Boolean.valueOf(String) 可以返回 null 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23393299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:47:15  来源:igfitidea点击:

Can Boolean.valueOf(String) return null?

javaboolean

提问by jlars62

Can Boolean.valueOf(String)ever return null? From what I can see in the java docs, the docs only specify when it returns true. Is false always returned otherwise, or can null be returned? I have not been able to get it to return null in the tests I have done, but I would like to be sure.

可以Boolean.valueOf(String)返回null吗?从我在 java docs 中可以看到,文档仅指定何时返回 true。否则总是返回false,还是可以返回null?在我所做的测试中,我无法让它返回 null,但我想确定一下。

Essentially, I want to know if the following code is safe from a NullPointerException:

本质上,我想知道以下代码对于 NullPointerException 是否安全:

boolean b = Boolean.valueOf(...); 

采纳答案by yshavit

The docs pretty much answer it: no. It'll return a Booleanrepresenting a true or false.

文档几乎回答了它:不。它将返回一个Boolean代表真或假的。

The code is also available:

代码也可用

public static Boolean valueOf(String s) {
    return toBoolean(s) ? TRUE : FALSE;
}

回答by Dan K.

No it will not. If null is placed within the argument or if a string is set to null it will return a boolean value of false. You can see expected inputs and outputs in the Java docs: http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html#booleanValue()

不,不会。如果 null 被放置在参数中或者如果一个字符串被设置为 null,它将返回一个布尔值 false。您可以在 Java 文档中看到预期的输入和输出:http: //docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html#booleanValue()

回答by Dan K.

No, this is impossible. See the source code of the class Boolean:

不,这是不可能的。查看类的源代码Boolean

public static Boolean valueOf(String s) {
    return toBoolean(s) ? TRUE : FALSE;
}

.. and then:

.. 进而:

private static boolean toBoolean(String name) {
   return ((name != null) && name.equalsIgnoreCase("true"));
}

回答by Stan

Actually it could cause NPE but can not return null. Try this:

实际上它可能会导致 NPE 但不能返回 null。尝试这个:

Boolean bNull = null;
System.print(Boolean.valueOf(bNull)); // -> NPE!

This happens cuz Boolean.valueOf()accepts Stringor booleanvalues. Since bNullis of type Booleanjava tries to unbox bNullvalue to pass it as booleanwhich causes NPE. Its funny but stupid actually... Also there is no Boolean.valueOf()for Number.

这是因为Boolean.valueOf()接受Stringboolean值。由于bNullBooleanjava类型,因此尝试取消装箱bNull值以将其作为boolean导致 NPE传递。它很有趣但实际上很愚蠢......也没有Boolean.valueOf()for Number