跳到主要内容

09、Java 21 新特性 - 字符串模板(预览)

预览阶段功能

使用字符串模板(String Templates)增强Java编程语言。字符串模板通过将文本与嵌入的表达式和模板处理器耦合来生成专门的结果,从而补充Java现有的字符串文本和文本块。这是一个预览语言功能和API。

String template(预览功能)

作为本版本的预览功能推出。字符串模板是对 Java 现有字符串字面量和文本块的补充,它将字面文本与嵌入式表达式和模板处理器结合起来,从而产生专门的结果。

在Java SE 21之前,字符串的拼接可以用下述三种方式

public static void stringTestBefore21() {
   
     
        int a = 1;
        int b = 2;

        String concatenated = a + " times " + b + " = " + a * b;
        String format = String.format("%d times %d = %d", a, b, a * b);
        String formatted = "%d times %d = %d".formatted(a, b, a * b);
        System.out.println(concatenated);
        System.out.println(format);
        System.out.println(formatted);
}

Java SE 21可以用更直观的方法实现字符串的拼接

 public static void stringTest21() {
   
     
        int a = 1;
        int b = 2;
        String interpolated = STR. "\{ a } times \{ b } = \{ a * b }" ;
        System.out.println(interpolated);

        String dateMessage = STR. "Today's date: \{
   
     
                LocalDate.now().format(
                        // We could also use DateTimeFormatter.ISO_DATE
                        DateTimeFormatter.ofPattern("yyyy-MM-dd")
                ) }" ;
        System.out.println(dateMessage);
        int httpStatus = 200;
        String errorMessage = "error pwd";

        String json = STR. """
    {
      "httpStatus": \{ httpStatus },
      "errorMessage": "\{ errorMessage }"
    }""" ;
        System.out.println(json);
    }