Monday, February 11, 2013

Alternative Java MessageFormat

MessageFormat

I was working on providing I18N support in my Krail project, when I was reminded of the strange characteristics of the standard Java MessageFormat class (java.text.MesssageFormat) ... especially the handling of single quotes.

I thought maybe it had been improved in Java 7, but it seems not.  The javadoc still carries a warning:




Warning:
The rules for using quotes within message format patterns unfortunately have shown to be somewhat confusing. In particular, it isn't always obvious to localizers whether single quotes need to be doubled or not. Make sure to inform localizers about the rules, and tell them (for example, by using comments in resource bundle source files) which strings will be processed by MessageFormat. Note that localizers may need to use single quotes in translated strings where the original version doesn't have them.

The Alternative

I remember being thoroughly confused by MessageFormat and the "solution" offered by the javadoc hardly helpful.  So I started looking for an alternative.  I found quite a few posts also looking for alternatives but still no real solution.  

So I wrote one ... it is based on sl4j, who have a highly tuned message handling routine for logging but which requires the parameter values to be provided in the same order as the message parameters.  That makes perfect sense for logging, but does not work very well for I18N, where different languages put the parameter values in different orders.

So I took the easy option of providing my own MessageFormat class to take the parameters in any order, but then organise them so that the sl4j MessageFormatter can do its work.

The resulting code is here, and its companion test code here.  Even if you have no interest in the Krail project, you may find the alternative MessageFormat useful.

No comments:

Post a Comment