Consider the custom toString()
implementation of a bean:
@Override
public String toString() {
String.format(\"this is %s\", this.someField);
}
<
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")
);
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.
For a Java 7 solution that doesn't require external libraries:
String.format("this is %s", Objects.toString(this.someField, "?"));
You could just do
String.format("this is %s", (this.someField==null?"DEFAULT":this.someField));
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));
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