How to have placeholder for variable value in java text block
How can I put a variable into java text block?
Like
"""
{
...
"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
String.format(str,LocalDate.now());
From jeps 355 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 : But as side note from java-13 docs String.formatted​
is deprecated and suggested to use String.format(this, args).
This method is associated with text blocks, a preview language feature. Text blocks and/or this method may be changed or removed in a future release.
P.S. Java text blocks and the formatted(Object... args)
method are part of the Java language since Java version 15.