如何在Java文本块中使用变量值的占位符?
2022-09-03 01:47:04
您可以在文本块中用作占位符:%s
String str = """
{
"someKey": "someValue",
"date": %s,
}
"""
并使用 format() 方法替换它。
String.format(str, LocalDate.now());
来自 JEP 378 文档:
一个更干净的替代方法是使用 String::replace 或 String::format,如下所示:
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);
另一种选择涉及引入一个新的实例方法 String::formatted,它可以按如下方式使用:
String source = """
public void print(%s object) {
System.out.println(Objects.toString(object));
}
""".formatted(type);
尽管如此,在Java版本13中,该方法被标记为已弃用,因为Java版本15格式化(Object...args)
方法是Java语言的正式部分,与文本块功能本身相同。formatted()