How can I put a variable into Java Text Block?
Like this:
"""
{
"someKey": "someValue",
"date": "${LocalDate.now()}",
}
"""
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With