简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM