Consider the custom toString()
implementation of a bean:
@Override
public String toString() {
String.format(\"this is %s\", this.someField);
}
<
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, "?"));
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.
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
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