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", "rkdixit3@gmail.com");
           
            String format = "Hello {name}, your email is {email}.";
            String message = StrSubstitutor.replace(format,map,"{","}");
            System.out.println(message);
      }
}

Output:
Hello Rajesh, your email is rkdixit3@gmail.com.

7 comments:

Related Posts Plugin for WordPress, Blogger...