Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
141 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...