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

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

    With java 8 you can now use Optional class for this:

    import static java.util.Optional.ofNullable;
    ...
    String myString = null;
    System.out.printf("myString: %s",
        ofNullable(myString).orElse("Not found")
    );
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-06 21:50

    For a Java 7 solution that doesn't require external libraries:

    String.format("this is %s", Objects.toString(this.someField, "?"));
    
    0 讨论(0)
  • 2021-02-06 21:50

    You could just do

    String.format("this is %s", (this.someField==null?"DEFAULT":this.someField));
    
    0 讨论(0)
  • 2021-02-06 21:56

    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));
    
    0 讨论(0)
  • 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> 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  
    
    0 讨论(0)
提交回复
热议问题