MessageFormat as Built-In Template Engine

The class MessageFormat (introduced with JDK 1.4) is also usable as an embedded template engine, suitable for creation of e.g. user notifications, serial emails etc.:

import static java.text.MessageFormat.format;
import static;
import static org.junit.Assert.assertThat;
import org.junit.Test;

public class MessageFormatTest {

    public void embeddedTemplateEngine() {
        String template = "Dear {0}, your {1} is {2}!";
        String expected = "Dear Developer, your micro is macro!";
        String actual = format(template, "Developer", "micro", "macro");
        assertThat(actual, is(expected));

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home:


MessageFormat has one big advantage over String.format(), which is the "choice" format:

{0,choice,0#no|1#one|1<more than one}

And it could be nested too.


Posted by Robert on November 09, 2016 at 05:25 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments