java.lang.String#isEmpty() 与 org.apache.commons.lang.StringUtils#isEmpty()

java.lang.String#isEmpty() vs org.apache.commons.lang.StringUtils#isEmpty()

虽然 oracles 方法的描述说它 returns 仅当字符串的长度为 0 时才为真,但字符串实用程序方法描述说该方法还检查字符串是否为 'null'。那我应该用什么方法呢?如果字符串的长度为 0(例如“”),则它自动不是 'null',或者如果我将字符串设为 'null',然后使用 oracles 方法检查其是否为空,我将得到 'false',那么 apaches 方法的 nullcheck 不是多余的,还是我的想法完全错误?请帮助我了解其中的区别!

我倾向于始终使用 apache 版本。 Oracle 版本要求您有一个非空字符串,因为它是一个实例方法,例如

String s = null;
s.isEmpty(); <--- throws a NullPointerException
StringUtils.isEmpty(s); <--- returns true

如果您不想在您的项目中包含 commons-lang,您可以使用

实现相同的功能
s != null && s.isEmpty()

当您不知道是否已设置字符串时,Apache 方法很有用。

if (s != null && !s.isEmpty()) {
    System.out.print(s)
}

if (!StringUtils.isEmpty(s)) {
    System.out.print(s)
}

会让你的代码更简洁