I want to get string values of my fields (they can be type of long string or any object),
if a field is null then it should return empty string, I did this with guava;
nullToEmpty(String.valueOf(gearBox)) nullToEmpty(String.valueOf(id)) ...
But this returns null if gearbox is null! Not empty string because valueOf methdod returns string "null" which leads to errors.
Any Ideas?
EDIt: there are 100s fields I look for something easy to implement
The Java programming language distinguishes between null and empty strings. An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters.
Empty string is a blank value,means the string does not have any thing. Show activity on this post. No method can be invoked on a object which is assigned a NULL value. It will give a nullPointerException .
isEmpty() String method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false.
Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string.
You can use Objects.toString()
(standard in Java 7):
Objects.toString(gearBox, "") Objects.toString(id, "")
From the linked documentation:
public static String toString(Object o, String nullDefault)
Returns the result of calling
toString
on the first argument if the first argument is not null and returns the second argument otherwise.Parameters:
o
- an objectnullDefault
- string to return if the first argument isnull
Returns:
the result of callingtoString
on the first argument if it is notnull
and the second argument otherwise.See Also:
toString(Object)
For java 8 you can use Optional approach:
Optional.ofNullable(gearBox).orElse(""); Optional.ofNullable(id).orElse("");
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