Wednesday, July 31, 2013

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}. Since I'm used to Drupal's format_string() function, here's a better alternative. Apache Commons has a StrSubstitutor class which allows use of named placeholders. Instead of using:

String template = "Welcome {0}!  Your last login was {1}";
String output = MessageFormat.format(template1, new Object[] { "gabe", new Date().toString() });

You can now do:

String template = "Welcome ${username}!  Your last login was ${lastlogin}";

Map data = new HashMap();
data.put("username", "gabe");
data.put("lastlogin", new Date().toString());
  
String output2 = StrSubstitutor.replace(template2, data);

Although StrSubstitutor is a bit more verbose, but it helps when you're handling lots of key/value pairs.

4 comments:

sai said...

Pleasant Tips..Thanks for Sharing….We keep up hands on approach at work and in the workplace, keeping our business pragmatic, which recommends we can help you with your tree clearing and pruning in an invaluable and fit way.
Data Science training in Chennai | Data Science Training Institute in Chennai
Data science online training | online Data Science certification Training-Gangboard

priya said...

Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
Data Science Training in Chennai
Data Science course in anna nagar
Data Science course in chennai
Data science course in Bangalore
Data Science course in marathahalli

Jayalakshmi said...

Nice blog, really I feel happy to see this useful blog… Thanks for sharing this valuable information to our vision....
java training in chennai

java training in tambaram

aws training in chennai

aws training in tambaram

python training in chennai

python training in tambaram

selenium training in chennai

selenium training in tambaram

deiva said...

Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.

oracle training in chennai

oracle training in omr

oracle dba training in chennai

oracle dba training in omr

ccna training in chennai

ccna training in omr

seo training in chennai

seo training in omr