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 guav
Use an inline null check
gearBox == null ? "" : String.valueOf(gearBox);
Since you're using guava:
Objects.firstNonNull(gearBox, "").toString();
If you don't mind using Apache commons, they have a StringUtils.defaultString(String str) that does this.
Returns either the passed in String, or if the String is null, an empty String ("").
If you also want to get rid of "null"
, you can do:
StringUtils.defaultString(str).replaceAll("^null$", "")
or to ignore case:
StringUtils.defaultString(str).replaceAll("^(?i)null$", "")
If alternative way, Guava provides Strings.nullToEmpty(String)
.
Source code
String str = null;
str = Strings.nullToEmpty(str);
System.out.println("String length : " + str.length());
Result
0
In Java 9+ use : Objects.requireNonNullElse (obj, defaultObj) https://docs.oracle.com/javase/9/docs/api/java/util/Objects.html#requireNonNullElse-T-T-
//-- returns empty string if obj is null
Objects.requireNonNullElse (obj, "")
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 object
nullDefault
- 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)