How to format message with argument names instead of numbers?

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


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].


See StrSubstitutor from org.apache.commons.lang3:

Map valuesMap = HashMap();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);

// resolvedString: "The quick brown fox jumped over the lazy dog."