Apache 的 StringUtils.isBlank(str) 与 Guava 的 Strings.isNullOrEmpty(str):您应该定期检查空格吗?
使用
StringUtils.isBlank(str)
Apache commons-lang 有什么优势吗?
相比
Strings.isNullOrEmpty(String string)
与 Google Guava
?我想替换它们在 Java 项目中使用的数百个案例:
if(str == null || str.isEmpty())
Guava 的 isNullOrEmpty 似乎是我项目中上述用法的直接替代。
但更多人似乎使用 Apache 的 isBlank 方法基于我对 SO 问题的阅读。
唯一的区别似乎是 StringUtils.isBlank(str)
除了检查字符串是否为 null 或空之外,还检查空格。
通常检查字符串是否有空格是个好主意,或者这会在代码中产生与 Guava 更简单的检查不同的结果吗?
Is there any advantage in using
StringUtils.isBlank(str)
from Apache commons-lang.
vs
Strings.isNullOrEmpty(String string)
from Google Guava?
I want to replace hundreds of cases of they following usage in a Java project:
if(str == null || str.isEmpty())
Guava's isNullOrEmpty seems to be a direct replacement for the usage above in my project.
But more people seem to use Apache's isBlank method based on my reading of S.O. questions.
The only difference seems to be that StringUtils.isBlank(str)
also checks for whitespace in addition to checking whether the string is null or empty.
Normally is it a good idea to check a String for whitespace or could that produce a different result in your code than Guava's simpler check?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您想使用 Guava 复制 isBlank 行为,我将使用以下方法:
Strings.nullToEmpty(str).trim().isEmpty()
If you want to use Guava to replicate the isBlank behaviour, I would use the following method instead:
Strings.nullToEmpty(str).trim().isEmpty()
当您必须接受人类的输入时,您应该宽容并从他们输入的任何文本中去除前导和尾随空格,如果这在特定应用程序中有意义的话。
也就是说,使用 isBlank 还只是半生不熟。您还需要在进一步处理字符串之前
修剪
字符串。因此,我建议在使用isNullOrEmpty
检查之前使用s = trim(s);
。When you have to accept input from human beings, you should be forgiving and strip leading and trailing whitespace from whatever text they type, if it makes sense in the particular application.
That said, using
isBlank
is only halfbaked. You also need totrim
the strings before processing them further. So I suggest to uses = trim(s);
before checking withisNullOrEmpty
.StringUtils.isBlank(str)
与Strings.isNullOrEmpty(String string)
有很大不同StringUtils.isBlank(str)
is very much different thanStrings.isNullOrEmpty(String string)
isBlank
被高估了。直接从输入字段读取用户文本的 UI 代码可以一劳永逸地修剪空白,然后您就可以不再担心它。isBlank
is incredibly overrated. UI code that reads user text straight out of input fields can trim whitespace once and for all, and then you can stop worrying about it.Guava 或多或少的目标是成为 Apache Commons 的“下一代”替代品。除了一致地使用其中之一之外,使用 isBlank() 与 isNullOrEmpty() 之间实际上没有太大的实际区别。
Guava is more or less targeted towards being a 'next generation' replacement of Apache Commons. There really isn't much practical difference between using isBlank() vs isNullOrEmpty() beyond using one or the other consistently.