java的字符串模板

java的字符串模板

介绍

java如何解决字符串占位符的问题JEP 430

字符串在java中是如何构造的

在编程中,字符串是无处不在的。在编码过程中,要不断的构造字符串

直接使用连字符+

对于很短的字符连接是很方便的,但对于多个+操作,就十分麻烦了
并且很难读

StringBuffer StringBuilder

可以方便的操作对象中的字符;但是,对于构造器模式,这样编码显得太繁冗

String Formatter

String composeUsingFormatters(String feelsLike, String temperature, String unit) {
    return String.format("Today's weather is %s, with a temperature of %s degrees %s", 
      feelsLike, temperature, unit);
}

对位置十分敏感;对维护/更改不友好

MessageFormat

String composeUsingMessageFormatter(String feelsLike, String temperature, String unit) {
    return MessageFormat.format("Today''s weather is {0}, with a temperature of {1} degrees {2}",
      feelsLike, temperature, unit);
}

Formatter有类似的缺点,并且不符合习惯

字符串模板

可以解决上述问题

目标

  1. 可以在编译时运行,并且简化字符串值处理过程
  2. 增强可读性
  3. 相对于其他语言,减少模板出现的文图/bug
  4. java库可以自定义模板

模板表达式

模板表达式不仅仅针对字符串,还有其他结构化文本。
三种类型的模板

  1. 处理器
  2. 包含带有嵌入表达式的数据的模板
  3. (.)字符

模板处理器

模板处理器负责计算嵌入式表达式(模板),并在运行时将其与字符串文本组合以生成最终字符串。

STR 模板处理器

样例

String interpolationUsingSTRProcessor(String feelsLike, String temperature, String unit) {
    return STR
      . "Today's weather is \{ feelsLike }, with a temperature of \{ temperature } degrees \{ unit }" ;
}


String interpolationOfJSONBlock(String feelsLike, String temperature, String unit) {
    return STR
      . """
      {
        "feelsLike": "\{ feelsLike }",
        "temperature": "\{ temperature }",
        "unit": "\{ unit }"
      }
      """ ;
}


String interpolationWithExpressions() {
    return STR
      . "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }";
}

FMT 模板处理器

String interpolationOfJSONBlockWithFMT(String feelsLike, float temperature, String unit) {
    return FMT
      . """
      {
        "feelsLike": "%1s\{ feelsLike }",
        "temperature": "%2.2f\{ temperature }",
        "unit": "%1s\{ unit }"
      }
      """ ;
}

模板表达式的计算

STR
  . "Today's weather is \{ feelsLike }, with a temperature of \{ temperature } degrees \{ unit }" ;
// 等价于下面两行

StringTemplate str = RAW
  . "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }" ;
return STR.process(str);

字符串内插和字符串模板

更安全,相对于其他语言的字符串模板

参考

java-21-string-templates

posted @ 2023-10-12 20:15  漫步ing  阅读(325)  评论(0编辑  收藏  举报