Get empty string when null

Spring picture Spring · Feb 21, 2014 · Viewed 87.4k times · Source

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

Answer

arshajii picture arshajii · Feb 21, 2014

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 is null

Returns:
the result of calling toString on the first argument if it is not null and the second argument otherwise.

See Also:
toString(Object)