Make String.format("%s", arg) display null-valued arguments differently from "null"

Consider the custom toString() implementation of a bean:

@Override
public String toString() {
    String.format("this is %s", this.someField);
}

This yields this is null if someField is null.

Is there a way to override the default null string representation of null-valued arguments to another text, i.e., ? without calling explicitly replaceAll(...) in the toString method?

Note: The bean inherits from a superclass that could implement Formattable (http://docs.oracle.com/javase/7/docs/api/java/util/Formattable.html) but I just don't seem to understand how to make this work.

EDIT: The snippet is over-simplified for the sake of example but I'm not looking for ternary operator solutions someField==null ? "?" : someField because:

  • there can be (potentially) a great many fields involved in toString() so checking all fields is too cumbersome and not fluent.
  • other people whom I have little control over (if any) are writing their own subclasses.
  • if a method is called and returns null that would either imply calling the method twice or declaring a local variable.

Rather, can anything be done using the Formattable interface or having some custom Formatter (which is final btw.)?


Solution 1:

With java 8 you can now use Optional class for this:

import static java.util.Optional.ofNullable;
...
String myString = null;
System.out.printf("myString: %s",
    ofNullable(myString).orElse("Not found")
);

Solution 2:

For a Java 7 solution that doesn't require external libraries:

String.format("this is %s", Objects.toString(this.someField, "?"));

Solution 3:

The nicest solution, in my opinion, is using Guava's Objects method, firstNonNull. The following method will ensure you will print an empty string if someField is ever null.

String.format("this is %s", MoreObjects.firstNonNull(this.someField, ""));

Guava docs.