Java 13已交付了期待已久的多行字符串或Text Blocks 。 您不再需要连接跨越多行的字符串或转义特殊字符,这确实提高了代码的可读性。 文本块是一种预览语言功能 ,这意味着必须使用--enable-preview
标志在Java编译器和运行时中明确启用它们。
这是一个文本块的示例:
String textBlock = "" " <html> <body> <p style= "color:red" >This is a text block</p> </body> </html> "" ";
如上所示,一个文本块用三个双引号( """
)引起来, """
开头不能跟任何非空白字符,即实际文本必须在开头定界符之后的行上开始。 您无需在文本块内转义任何特殊字符,这太好了!
在Java的早期版本中,您将不得不这样编写:
final String old = "<html>\n" + "\t<body>\n" + "\t\t<p style=\"color:red\">This is a text block</p>\n" + "\t</body>\n" + "</html>" ;
实际上,在此示例中, textBlock == old
因为两者的内容完全相同,并且在String
池中引用的对象相同。
现在,通过考虑以下两个文本块,看看如何处理前导空白:
String textBlock1 = "" " <html> <body> <p style= "color:red" >This is a text block</p> </body> </html> "" "; String textBlock2 = "" " <html> <body> <p style= "color:red" >This is a text block</p> </body> </html> "" ";
如果您打印出这两个文本块,则第一个打印为:
<html> <body> <p style= "color:red" >This is a text block</p> </body> </html>
第二个是:
<html> <body> <p style= "color:red" >This is a text block</p> </body> </html>
文本块中任何行上的最左非空白字符或最左边的分隔符确定整个块的“起点”,并且从该起点开始,每行都保留空白。
要注意的另一点是,在文本块中删除了每行末尾的空白,但是您可以使用八进制转义序列\040
来保留它,如下所示:
String octal = "" " line 1 \ 040 line 2 line "" ";
翻译自: https://www.javacodegeeks.com/2019/10/java-13-text-blocks.html