在这个密码里。
public class Test {
public static void testFun(String str) {
if (str == null | str.length() == 0) {
System.out.println("String is empty");
} else {
System.out.println("String is not empty");
}
}
public static void main(String [] args) {
testFun(null);
}
}
我们将一个null
值传递给函数testFun
。编译很好,但是在运行时给出了一个NullPointerException
,这是我没想到的。为什么要抛出一个异常,而不是将if
条件计算给true
并打印"String是空的“?
假设传递给testFun
的实际参数的值是从某个进程生成的。假设该进程错误地返回了一个null
值,并将其输入testFun。如果是这样的话,如何验证传递给函数的值是否为空?
一种(奇怪的)解决方案可能是将形式参数分配给函数中的某个变量,然后对其进行测试。但是,如果有许多变量传递给函数,这可能会变得乏味和不可行。那么,在这种情况下如何检查空值呢?
发布于 2012-08-26 11:59:52
编辑准确地显示了工作代码和不工作代码之间的区别。
此检查总是计算这两种条件,如果str
为null,则抛出异常:
if (str == null | str.length() == 0) {
而这(使用||
而不是|
)是短路的--如果第一个条件计算为true
,则第二个条件不计算。
有关||
的描述,请参阅JLS的section 15.22.2;二进制|
,请参阅section 15.22.2。但是,第15.24节的介绍是很重要的一点:
条件-或操作符\x运算符类似于_
发布于 2015-06-25 00:48:44
您可以使用StringUtils
import org.apache.commons.lang3.StringUtils;
if (StringUtils.isBlank(str)) {
System.out.println("String is empty");
} else {
System.out.println("String is not empty");
}
也请看这里:StringUtils.isBlank() vs String.isEmpty()
isBlank
示例:
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
发布于 2012-08-26 11:50:55
这里的问题是,在您的代码中,程序调用'null.length()‘,如果传递给该函数的参数为null,则不定义该函数。这就是抛出异常的原因。
https://stackoverflow.com/questions/12133328
复制相似问题