Java Text Block

JDK 15 新增的特性
目的是簡化字串串接
語法為三個引號

範例:

String oldString = "<html>" +
                "  <head>" +
                "    <title>Example</title>" +
                "  </head>" +
                "  <body>" +
                "    <p>" +
                "      <a href=\"https://www.gonxx.com/\">link</a>" +
                "    </p>" +
                "  </body>" +
                "</html>";

String newString = """
                <html>
                  <head>
                    <title>Example</title>
                  </head>
                  <body>
                    <p>
                      <a href="https://www.gonxx.com/">link</a>
                    </p>
                  </body>
                </html>
                """;

優點:

  • 省略串接 +
  • 省略跳脫字元 "
  • 省略換行 \\n

但也帶來幾個問題

因為預設換行,如果不想換行

String string = """
                line1\
                line2
                """;
System.out.println(string); //line1line2

預設會 trim,如果要保留結尾的空白

String string = """
                line1  \s\
                line2
                """;
System.out.println(string); //line1  line2

如果要串接變數,要用 replace

String json = """
                {
                  "name": "$name",
                  "message": "$message"
                }
                """
                .replace("$name", name)
                .replace("$message", message);

發佈留言