Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java MessageFormat Null Values

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"?

like image 527
markush81 Avatar asked Jul 08 '14 22:07

markush81


1 Answers

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, ""));
like image 155
Makoto Avatar answered Sep 20 '22 12:09

Makoto