null 和 StringUtils.isBlank() 之间的区别

Differences between null and StringUtils.isBlank()

我想检查一个String是否为空,我想知道下面的区别,在什么情况下哪个更好

特别是因为我在使用 "isNotBlank" 时遇到此错误:"cannot be cast to java.lang.String".

this.text.getData() != null <--- works perfectly fine.
StringUtils.isNotBlank((String)this.text.getData()) <- doesn't work.

如果 "null" 不是最佳解决方案,我可以使用什么?

如果您希望任何非空的数据都是字符串,那么 this.text.getData() != null 可能有效,但您的代码稍后会起作用 关于 class 转换问题以及转换为 String 的事实 不工作显示更深层次的问题。

如果 'data' 可以是某种类型的对象,那么 StringUtils 根本不是正确的解决方案,空检查 是正确的做法!

isNotBlank() 检查字符串是否不为空 ("")、不为空且不为空白。

public static boolean isNotBlank(String str)
Checks if a String is not empty (""), not null and not whitespace only.

请参阅文档 isNotBlank

!= null 仅检查对象是否为 null

如果我使用 "isNotBlank" "cannot be cast to java.lang.String".

,我会收到此错误

那是因为您的 getData() return 可能不是字符串,无法转换为字符串。

而且您需要知道您可以对任何类型的对象执行 != null 但要执行 isNotBlank() 它应该是一个字符串。