我正在传递一个来自XML文件的accountid作为输入,如下所示,稍后将对其进行解析并将在我们的代码中使用:
<accountid>123456</accountid>
<user>pavan</user>
Run Code Online (Sandbox Code Playgroud)
问题是如果没有传递任何内容(accoutnid中的空值)作为accountid传递,我无法在Java代码中处理这种情况.我试过这个,但我没有成功:
if (acct != null||acct==""||acct.equals(""))
{
// the above is not working
}
Run Code Online (Sandbox Code Playgroud)
我能够使用以下方法成功处理此问题:
if(!acct.isEmpty())
{
// thisis working
}
Run Code Online (Sandbox Code Playgroud)
我们可以依靠这个String.isEmpty()方法来检查一个String?的空状态吗?这有效吗?
Jon*_*eet 116
不,绝对不是-因为如果acct为空,它甚至不会得到对isEmpty......它会立即抛出NullPointerException.
你的测试应该是:
if (acct != null && !acct.isEmpty())
Run Code Online (Sandbox Code Playgroud)
注意&&这里的使用,而不是你||之前的代码; 还要注意如何在你前面的代码,你的情况是错误的呢-即使&&你只输入了if身体,如果acct 是一个空字符串.
或者,使用番石榴:
if (!Strings.isNullOrEmpty(acct))
Run Code Online (Sandbox Code Playgroud)
lra*_*her 20
用StringUtils.isEmpty相反,它还会检查空.
例如:
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
Run Code Online (Sandbox Code Playgroud)
有关String Utils的官方文档,请参阅更多信息.
String.isEmpty()如果它为null,则不能使用.最好的方法是使用自己的方法来检查null或为空.
public static boolean isBlankOrNull(String str) {
return (str == null || "".equals(str.trim()));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85360 次 |
| 最近记录: |