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

Viewed 73242

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.)?

10 Answers

If you don't want to use replaceAll(), You can assign a default text(String) for someField.

But if some time this may assign null again. So you can use validation for that case

 this.someField == null ? "defaultText" : this.someField

To avoid repeating ternary operator you can wrap it in more readable method that will check if your object is null and return some default value if it is true like

static <T> T changeNull(T arg, T defaultValue) {
    return arg == null ? defaultValue : arg;
}

usage

String field = null;
Integer id = null;
System.out.printf("field is %s %n", changeNull(field, ""));
System.out.printf("id is %d %n", changeNull(id, -1));
System.out.printf("id is %s %n", changeNull(field, ""));

output:

field is  
id is -1 
id is  

You could just do

String.format("this is %s", (this.someField==null?"DEFAULT":this.someField));

To keep the original value of someField (in case null is a valid value), you can use a ternary operator.

String.format("This is %s", (this.someField == null ? "unknown" : this.someField));
Related