有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (1) 个答案

  1. # 1 楼答案

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

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

    并用format替换它

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

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

    注意:但是作为java-13文档的旁注String.formatted​被弃用,建议使用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.