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

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

    From java 7, you can use Objects.toString(Object o, String nullDefault).

    Applied to your example: String.format("this is %s", Objects.toString(this.someField, "?"));

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-06 22:08
    public static String format(String format, Object... args){
        for (int i=0;i<args.length;i++){
            if (args[i]==null) args[i]="";
        }
        return String.format(format,args);
    }
    

    then use the method ,ok

    0 讨论(0)
提交回复
热议问题