如何在 Java 文本块中为变量值设置占位符?

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

如何将 变量 放入 Java Text Block

像这样:

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

}
"""

您可以在文本块中使用 %s 作为 占位符

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

并使用format()方法替换它。

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

来自 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);

注意

尽管在 Java 版本 13 中 formatted() 方法被标记为 deprecated, since Java version 15 formatted(Object... args) 方法正式成为 Java 语言的一部分,与文本块功能相同本身。