'How to have placeholder for variable value in Java Text Block?

How can I put a variable into Java Text Block?

Like this:

"""
{
    "someKey": "someValue",
    "date": "${LocalDate.now()}",

}
"""


Solution 1:[1]

You can use %s as a placeholder in text blocks:

String str = """
{
    "someKey": "someValue",
    "date": %s,
}
"""

and replace it using format() method.

String.format(str, LocalDate.now());

From JEP 378 docs:

A cleaner alternative is to use String::replace or String::format, as follows:

String code = """
          public void print($type o) {
              System.out.println(Objects.toString(o));
          }
          """.replace("$type", type);

String code = String.format("""
          public void print(%s o) {
              System.out.println(Objects.toString(o));
          }
          """, type);

Another alternative involves the introduction of a new instance method, String::formatted, which could be used as follows:

String source = """
            public void print(%s object) {
                System.out.println(Objects.toString(object));
            }
            """.formatted(type);

NOTE

Despite that in the Java version 13 the formatted() method was marked as deprecated, since Java version 15 formatted(Object... args) method is officially part of the Java language, same as the Text Blocks feature itself.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 informatik01