theme: orange
Text Blocks
文本块最小化表示多行字符串所需的 一种Java 语法,它可以用来代替任何按惯例在双引号中添加的字符串。在文本块之前,如果我们必须打印一个多行字符串,我们将需要使用分隔符,连接等。
例如,下面的代码将在一行中给出完整的字符串
System.out.print("Hey There " + "What's up?? " + "How was your vacation?? " + ";)");
输出:
Hey There What's up?? How was your vacation?? ;)
为了在下一行打印它们,我们必须将上面的代码修改为下面给出的代码,
System.out.print("Hey There \n" + "What's up?? \n" + "How was your vacation?? \n" + ";)");
使用文本块,我们可以将上面的代码重写为下面给出的代码,
System.out.print(""" Hey There What's up?? How was your vacation?? ;) """);
文本块也可以用来代替标准字符串。例如,下面显示的两个字符串具有相同的含义:
//Text Block printMsg(""" Print This!! """); // String in Double Quotes printMsg("Print this!");
Switch Expressions (JEP 354)
我们最初在 JDK 12中看到了Switch Expressions。13的Switch Expressions通过添加一个新的 yield 语句在前一版本的基础上构建。
使用 yield,我们现在可以有效地从 switch 表达式返回值:
@Test @SuppressWarnings("preview") public void whenSwitchingOnOperationSquareMe_thenWillReturnSquare() { var me = 4; var operation = "squareMe"; var result = switch (operation) { case "doubleMe" -> { yield me * 2; } case "squareMe" -> { yield me * me; } default -> me; }; assertEquals(16, result); }
正如我们所看到的,现在很容易实现的战略模式使用新的切换。
Text Blocks
多行字符串的文本块,如嵌入式 JSON、 XML、 HTML 等。
为了将 JSON 嵌入到我们的代码中,我们将它声明为 String literal:
String JSON_STRING = "{\r\n" + ""name" : "namestr",\r\n" + ""website" : "https://www.%s.com/"\r\n" + "}";
现在让我们使用 String 文本块编写相同的 JSON:
String TEXT_BLOCK_JSON = """ { "name" : "namestr", "website" : "https://www.%s.com/" } """;
很明显,没有必要转义双引号或添加回车。通过使用文本块,嵌入的 JSON 更易于编写,更易于阅读和维护。
此外,所有的 String 函数都是可用的:
@Test public void whenTextBlocks_thenStringOperationsWorkSame() { assertThat(TEXT_BLOCK_JSON.contains("namestr")).isTrue(); assertThat(TEXT_BLOCK_JSON.indexOf("www")).isGreaterThan(0); assertThat(TEXT_BLOCK_JSON.length()).isGreaterThan(0); }
另外,java.lang.String 现在有三个新的方法来操作文本块:
- stripIndent ()——模仿编译器去除附带的空白
- translateEscapes ()-将转义序列(如“ t”)翻译为“ t”
- Formatted ()-与 String: : : format 的工作方式相同,但用于文本块
让我们快速看一下 String: : : 格式化的例子:
assertThat(TEXT_BLOCK_JSON.formatted("baeldung").contains("www.baeldung.com")).isTrue(); assertThat(String.format(JSON_STRING,"baeldung").contains("www.baeldung.com")).isTrue();
当然还有其它的新特性,包括但不限于:
- Dynamic CDS Archives (JEP 350)
- ZGC: Uncommit Unused Memory (JEP 351)
- Reimplement the Legacy Socket API (JEP 353)