How to have placeholder for variable value in java text block

前端 未结 1 639
感动是毒
感动是毒 2021-01-14 08:12

How can I put a variable into java text block?
Like

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


        
相关标签:
1条回答
  • 2021-01-14 09:13

    You can use %s as 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.

    0 讨论(0)
提交回复
热议问题