[英]Differences between null and StringUtils.isBlank()
I want to check if a String is empty or not and I would like to know the differences between the following and which one is better and on which occasions. 我想检查一个String是否为空,我想知道以下哪个更好,哪个更好以及在哪些情况下。
Specially because I'm getting this error if I use "isNotBlank": "cannot be cast to java.lang.String". 特别是因为我使用“isNotBlank”时出现此错误:“无法转换为java.lang.String”。
this.text.getData() != null <--- works perfectly fine.
StringUtils.isNotBlank((String)this.text.getData()) <- doesn't work.
If "null" is not the best solution, what could I use? 如果“null”不是最佳解决方案,我可以使用什么?
If you expect any data that is not null to be a String then this.text.getData() != null
might work but your code will later on have a class cast problem and the fact that the cast to String is not working shows a deeper problem. 如果您希望任何非null的数据都是String,那么
this.text.getData() != null
可能会起作用,但是您的代码稍后会出现类强制转换问题,并且转换为String的操作不会显示更深的问题。
If it is OK for 'data' to be some object of some type, then StringUtils
is simply not the right solution and the Null-check is the right thing to do! 如果'data'可以作为某种类型的某个对象,那么
StringUtils
根本就不是正确的解决方案,Null-check是正确的做法!
isNotBlank()
Checks if a String is not empty (""), not null and not whitespace only. isNotBlank()
检查String是否为空(“”),不是null而不是空白。
public static boolean isNotBlank(String str)
public static boolean isNotBlank(String str)
Checks if a String is not empty (""), not null and not whitespace only.检查String是否为空(“”),不是null而不是空白。
See Doc isNotBlank 请参阅Doc isNotBlank
!= null
check only if the object is null
!= null
仅在对象为null
检查
I'm getting this error if I use "isNotBlank" "cannot be cast to java.lang.String". 如果我使用“isNotBlank”“无法转换为java.lang.String”,我会收到此错误。
That's because may be your getData()
return something other than String and that can't be casted to String. 那是因为你的
getData()
可能会返回除String之外的其他内容,并且无法将其转换为String。
And you need to know you can do != null
with any type of object but to do isNotBlank()
it should be a String. 你需要知道你可以做
!= null
对于任何类型的对象都是!= null
,但是要做isNotBlank()
它应该是一个String。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.