Friday, 20 May 2016

Java Message Format Using Named Placeholder

The Java MessageFormat class allows user to pre-define a string with placeholders and then fill the placeholders with actual strings later to construct a proper message.

It's all fine if you're used to numbered placeholders e.g. {0} and {1}.

Apache Commons has a StrSubstitutor class which allows use of named placeholders.
Although StrSubstitutor is a bit more verbose, but it helps when you're handling lots of key/value pairs.

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.text.StrSubstitutor;

public class MessagePlaceHolder {
      public static void main(String[] args) {
            Map<String,String> map = new HashMap<String, String>();
            map.put("name", "Rajesh");
            map.put("email", "");
            String format = "Hello {name}, your email is {email}.";
            String message = StrSubstitutor.replace(format,map,"{","}");

Hello Rajesh, your email is

1 comment:

  1. Amazing Article, thank you!. I am very glad to read your informative & practical blog. Kindly keep updating your blog. Java Developer is a wonderful career for IT students.To start Dream Career to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training from India .


Related Posts Plugin for WordPress, Blogger...