adam bien's blog

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.