How to format message with argument names instead of numbers?

user550738 picture user550738 · Mar 28, 2011 · Viewed 48.7k times · Source

I have something like:

String text = "The user {0} has email address {1}."
// params = { "Robert", "[email protected]" }
String msg = MessageFormat.format(text, params);

This isn't great for me, because sometimes my translators are not sure what goes in the {0} and {1}, also it would be nice to be able to reword the messages without worrying about the order of the args.

I'd like to replace the arguments with readable names instead of numbers. Something like this:

String text = "The user {USERNAME} has email address {EMAILADDRESS}."
// Map map = new HashMap( ... [USERNAME="Robert", EMAILADDRESS="[email protected]"]
String msg = MessageFormat.format(text, map);

Is there an easy way to do this?

Thanks! rob

Answer

GuruKulki picture GuruKulki · Mar 28, 2011

You can use MapFormat for this. Find out the details here:

http://www.java2s.com/Code/Java/I18N/AtextformatsimilartoMessageFormatbutusingstringratherthannumerickeys.htm

String text = "The user {name} has email address {email}.";
Map map = new HashMap();
map.put("name", "Robert");
map.put("email", "[email protected]");

System.out.println("1st : " + MapFormat.format(text, map));

OUTPUT:

1st : The user Robert has email address [email protected].