Java TextBlocks and String#replace 📎
String#replace
is useful for the substitution of multiple occurrences of
a placeholder.
In the following sample, two occurrences of the $name
String were replaced with a single replace
invocation:
@Test
public void textBlocks() {
var message = """
class $class{
String $name;
public String toString(){
return this.$name;
}
}
""".replace("$class", "Developer")
.replace("$name", "firstName");
System.out.println(message);
}
...prints:
class Developer{
String firstName;
public String toString(){
return this.firstName;
}
}
The old, JDK 1.5, String#replace method is useful for replacement of multiple placeholders with a single call, whereby the newer JDK 15 method: String#formatted relies on the Formatter syntax.
This post was inspired by the description of the: JEP 378: Text Blocks