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

前端 未结 10 1196
忘了有多久
忘了有多久 2021-02-06 21:22

Consider the custom toString() implementation of a bean:

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


        
10条回答
  •  死守一世寂寞
    2021-02-06 21:47

    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.

提交回复
热议问题