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.
Specially because I'm getting this error if I use "isNotBlank": "cannot be cast to 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?
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.
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!
isNotBlank() Checks if a String is not empty (""), not null and not whitespace only.
public static boolean isNotBlank(String str)
Checks if a String is not empty (""), not null and not whitespace only.
See Doc isNotBlank
!= null check only if the object is null
I'm getting this error if I use "isNotBlank" "cannot be cast to java.lang.String".
That's because may be your getData() return something other than String and that can't be casted to String.
And you need to know you can do != null with any type of object but to do isNotBlank() it should be a String.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With