Java Text Blocks (Java 15+)

Text Blocks(文字區塊)是 Java 15 引入的多行字串語法,使用三個雙引號 """ 來定義,讓多行文字更容易撰寫和閱讀。

基本語法

// 傳統寫法
String oldWay = "第一行\n" +
                "第二行\n" +
                "第三行";

// Text Block
String textBlock = """
    第一行
    第二行
    第三行
    """;

縮排處理

Text Block 會自動移除共同的前導空白:

String html = """
    <html>
        <body>
            <p>Hello</p>
        </body>
    </html>
    """;

// 實際結果(移除共同縮排):
// <html>
//     <body>
//         <p>Hello</p>
//     </body>
// </html>

控制縮排

// 結尾引號的位置決定縮排
String s1 = """
    Hello
    World
    """;  // 無縮排

String s2 = """
    Hello
    World
""";  // 保留縮排

換行控制

// 預設每行結尾有換行
String withNewlines = """
    Line 1
    Line 2
    Line 3
    """;

// 使用 \ 取消換行
String singleLine = """
    This is a very \
    long line that \
    continues here.""";
// 結果:"This is a very long line that continues here."

跳脫字元

// 雙引號不需要跳脫
String json = """
    {
        "name": "Alice",
        "age": 30
    }
    """;

// 需要三個連續雙引號時才要跳脫
String withQuotes = """
    她說:"你好!"
    他回答:\"""這是三個引號\"""
    """;

// 其他跳脫字元正常使用
String escaped = """
    Tab:\t換行:\n反斜線:\\
    """;

空白處理

// \s 保留尾端空白
String preserveSpace = """
    Name:    \s
    Value:   \s
    """;

// 結尾空白預設會被移除
String trimmed = """
    Hello   
    World   
    """;  // 行尾空白被移除

實用範例

HTML 模板

String html = """
    <!DOCTYPE html>
    <html>
    <head>
        <title>%s</title>
    </head>
    <body>
        <h1>%s</h1>
        <p>%s</p>
    </body>
    </html>
    """.formatted("標題", "歡迎", "這是內容");

JSON

String json = """
    {
        "users": [
            {"name": "Alice", "age": 25},
            {"name": "Bob", "age": 30}
        ],
        "total": 2
    }
    """;

SQL

String sql = """
    SELECT u.name, u.email, o.total
    FROM users u
    JOIN orders o ON u.id = o.user_id
    WHERE u.status = 'active'
      AND o.created_at > ?
    ORDER BY o.total DESC
    LIMIT 10
    """;

正規表達式

// 不需要雙重跳脫
String regex = """
    ^(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})$
    """.trim();

Pattern pattern = Pattern.compile(regex);

程式碼生成

String code = """
    public class %s {
        private %s %s;
        
        public %s get%s() {
            return this.%s;
        }
        
        public void set%s(%s %s) {
            this.%s = %s;
        }
    }
    """.formatted(
        "User", "String", "name",
        "String", "Name", "name",
        "Name", "String", "name", "name", "name"
    );

搭配 String 方法

String text = """
    Hello World
    """;

// 常用方法
text.trim();           // 移除前後空白
text.strip();          // 移除前後空白(Unicode 感知)
text.stripIndent();    // 移除縮排
text.translateEscapes(); // 處理跳脫字元
text.formatted(args);  // 格式化

// 範例
String raw = """
    \\n\\t
    """.translateEscapes();  // 變成實際的 \n\t

注意事項

// 開頭 """ 後必須換行
String invalid = """Hello""";  // 編譯錯誤

// 正確寫法
String valid = """
    Hello""";

// 空字串
String empty = """
    """;  // ""

Text Block vs 傳統字串

特性Text Block傳統字串
多行原生支援需要 \n 或 +
縮排自動處理手動處理
雙引號不需跳脫需要 "
可讀性較低

重點整理

  • 使用 """ 開始和結束
  • 開頭 """ 後必須換行
  • 自動移除共同的前導空白
  • 結尾引號位置決定最終縮排
  • \ 可取消換行,\s 保留尾端空白
  • 搭配 formatted() 進行字串插值
  • 非常適合 HTML、JSON、SQL、正規表達式等