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 org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;

public class MessageFormatTest {

    @Test
    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: airhacks.io.


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 8, Java 9: Bootstrap, Effective, Architectures, Single Page Apps, Progressive Web Apps, HTML 5, ES 6, CSS 3 and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

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.

Regards,
Robert

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

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License