A Guide to Java MessageFormat (or, How I Learned to Stop Worrying and Love Macros)
Wednesday, December 10th, 2008While working on an application for a client, I encountered some issues with Java’s MessageFormat. In particular, I needed to pass MessageFormat a string that contained single-quotes and curly braces that would be treated literally. This is an issue, because single-quotes and curly braces are special characters in MessageFormat land.
MessageFormat is designed to allow you to dynamically create a string based on a static pattern and a set of inputs. For example, this is from the MessageFormat JavaDoc:
Object[] testArgs = {new Long(3), "MyDisk"};
MessageFormat form = new MessageFormat(
"The disk \"{1}\" contains {0} file(s).");
System.out.println(form.format(testArgs));
// output, with different testArgs
output: The disk "MyDisk" contains 0 file(s).
output: The disk "MyDisk" contains 1 file(s).
output: The disk "MyDisk" contains 1,273 file(s).