Java StringTemplate of() Method

The StringTemplate.of() method in Java 21 is used to create StringTemplate instances from a given string. This guide will cover the method's usage, explain how it works, and provide examples to demonstrate its functionality.

Table of Contents

  1. Introduction
  2. of() Method Syntax
  3. Understanding of()
  4. Examples
    • Basic Usage
    • Using Named Placeholders
    • Using Positional Placeholders
  5. Real-World Use Case
  6. Conclusion

Introduction

The StringTemplate.of() method allows developers to create StringTemplate instances from strings that contain placeholders. These placeholders can later be replaced with actual values using the interpolate() method.

of() Method Syntax

There are two main overloads of the of() method:

  1. of(String template)
  2. of(String template, List<Object> fragments)

Syntax 1: of(String template)

public static StringTemplate of(String template)

Syntax 2: of(String template, List<Object> fragments)

public static StringTemplate of(String template, List<Object> fragments)

Parameters for of(String template):

  • template: The string containing the template with placeholders.

Parameters for of(String template, List<Object> fragments):

  • template: The string containing the template with placeholders.
  • fragments: A list of objects representing the fragments that make up the template.

Returns:

  • A StringTemplate instance created from the given string.

Understanding of()

The of() method is used to create a StringTemplate from a string. Placeholders within the string can be specified using the ${name} syntax for named placeholders or {index} syntax for positional placeholders. The method can be used to construct templates that can later be interpolated with actual values.

Examples

Basic Usage

To demonstrate the basic usage of of(), we will create a simple StringTemplate from a string with a placeholder.

Example

import java.lang.StringTemplate;

public class StringTemplateOfExample {
    public static void main(String[] args) {
        StringTemplate template = StringTemplate.of("Hello, ${name}!");
        System.out.println(template.interpolate(Map.of("name", "Alice")));
    }
}

Output:

Hello, Alice!

Using Named Placeholders

You can use the of() method to create a StringTemplate with named placeholders.

Example

import java.lang.StringTemplate;
import java.util.Map;

public class NamedPlaceholdersExample {
    public static void main(String[] args) {
        StringTemplate template = StringTemplate.of("Hello, ${name}! Today is ${day}.");

        String result = template.interpolate(Map.of(
            "name", "Alice",
            "day", "Monday"
        ));

        System.out.println(result);
    }
}

Output:

Hello, Alice! Today is Monday.

Using Positional Placeholders

You can use the of() method to create a StringTemplate with positional placeholders by using custom logic to replace placeholders.

Example

import java.lang.StringTemplate;
import java.util.Map;

public class PositionalPlaceholdersExample {
    public static void main(String[] args) {
        StringTemplate template = StringTemplate.of("Hello, {0}! You have {1} new messages.");

        Map<String, Object> values = Map.of(
            "0", "Alice",
            "1", 5
        );

        String result = interpolateWithPosition(template, values);
        System.out.println(result);
    }

    public static String interpolateWithPosition(StringTemplate template, Map<String, Object> values) {
        String result = template.interpolate();
        for (Map.Entry<String, Object> entry : values.entrySet()) {
            result = result.replace("{" + entry.getKey() + "}", entry.getValue().toString());
        }
        return result;
    }
}

Output:

Hello, Alice! You have 5 new messages.

Real-World Use Case

Generating Dynamic Emails

In a real-world scenario, you might need to generate dynamic emails based on templates. Using the StringTemplate.of() method, you can create templates with placeholders and later interpolate them with actual values.

Example

import java.lang.StringTemplate;
import java.util.Map;

public class DynamicEmailExample {
    public static void main(String[] args) {
        StringTemplate emailTemplate = StringTemplate.of("Dear ${name},\n\nYour order ${orderId} has been shipped on ${date}.");

        Map<String, Object> values = Map.of(
            "name", "John Doe",
            "orderId", "12345",
            "date", "June 25, 2024"
        );

        String emailContent = emailTemplate.interpolate(values);
        System.out.println(emailContent);
    }
}

Output:

Dear John Doe,

Your order 12345 has been shipped on June 25, 2024.

Conclusion

The StringTemplate.of() method in Java 21 provides a powerful way to create StringTemplate instances from strings containing placeholders. By using this method, you can construct templates that can be dynamically populated with actual values at runtime. Whether you are working with simple string templates or complex dynamic content, the StringTemplate.of() method offers a reliable tool for managing and creating string templates.

Comments