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

前端 未结 10 1197
忘了有多久
忘了有多久 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:57

    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 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  
    

提交回复
热议问题