Java MessageFormat Null Values

markush81 picture markush81 · Jul 9, 2014 · Viewed 7.7k times · Source

What is the best way to treat null values in Java MessageFormat

MessageFormat.format("Value: {0}",null);

=> Value: null

but actually a "Value: " would be nice.

Same with date

MessageFormat.format("Value: {0,date,medium}",null);

=> Value: null

a "Value: " whould be much more appreciated.

Is there any way to do this? I tried choice

{0,choice,null#|notnull#{0,date,dd.MM.yyyy – HH:mm:ss}}

which results in invalid choice format, what is correct to check for "null" or "not null"?

Answer

Makoto picture Makoto · Jul 9, 2014

MessageFormat is only null-tolerant; that is, it will handle a null argument. If you want to have a default value appear instead of something if the value you're working with is null, you have two options:

You can either do a ternary...

MessageFormat.format("Value: {0}", null == value ? "" : value));

...or use StringUtils.defaultIfBlank() from commons-lang instead:

MessageFormat.format("Value: {0}", StringUtils.defaultIfBlank(value, ""));