7

Is there any utility available to easily get the string representation of an arbitrary object if it exists and keep it null if it was null?

For example

String result = null;
if (object != null) {
    result = object.toString();
}

but less verbose.

I have looked into ObjectUtils and String.valueOf but neither returns just null itself. Both return default strings, i.e. the empty string or the string "null" instead of just null.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
awgtek
  • 1,483
  • 16
  • 28

1 Answers1

24

If I understand your problem, you can use that (java.util.Objects is here since JDK7):

Objects.toString(s, null); // return null if s is null, s.toString() otherwise

In fact, it works for every object.

NoDataFound
  • 11,381
  • 33
  • 59
  • `StringUtils.defaultString(s)` won't work, because it converts the value to an empty string, what I need is it to be null. – awgtek Jan 14 '20 at 21:50
  • 1
    I think then `Objects.toString(o, null)` is the only option. Would have liked to avoid the extra param though. – awgtek Jan 14 '20 at 21:51
  • 1
    You're right, but Objects.toString will more than likely work. – NoDataFound Jan 14 '20 at 21:52
  • An upside of the extra param is that it makes it clear to readers that you're intentionally handling null, and purposefully returning `null` as the result when the value is null. A lot of times null handling behavior is accidental and a source of bugs, so by using this approach, it's clear that you as the code writer (probably) thought through the null implications and chose that behavior. – M. Justin May 17 '21 at 15:33