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

前端 未结 10 1461
忘了有多久
忘了有多久 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 22:03

    A bit late on the subject, but this could be a quite clean-looking solution : First, create your own format method...

    private static String NULL_STRING = "?";
    
    private static String formatNull(String str, Object... args){
        for(int i = 0; i < args.length; i++){
            if(args[i] == null){
                args[i] = NULL_STRING;
            }
        }
    
        return String.format(str, args);
    }
    

    Then, use it as will...

    @Test
    public void TestNullFormat(){
        Object ob1 = null;
        Object ob2 = "a test";
    
        String str = formatNull("this is %s", ob1);
        assertEquals("this is ?", str);
    
        str = formatNull("this is %s", ob2);
        assertEquals("this is a test", str);
    }
    

    This eliminates the need for multiple, hard-to-read, ternary operators.

提交回复
热议问题