Characteristics of the increase in the text block JDK13

Summary

JDK13 added in the text block function. This article will have the following:

  1. What the new version of JDK added text block motive?
  2. How to use blocks of text
  3. Compile text block
  4. Connecting the text block

aims

  • Simplify string across multiple lines, avoiding special characters such as newline escape simplify writing Java programs.
  • Enhance the readability of the Java program in the string.

motivation

In Java, the expression typically require the use of type String String HTML, XML, SQL, or the like JSON format, and need to be escaped string assignment during the connecting operation, and to compile the code is difficult to read and this expression difficult to maintain.

Whether the text is the code from other programming languages, or natural language, said in a Java program in a short text, and long text of this Chinese need to have a common expression.

Therefore, the text block will improve the readability and writability Java programs.

HTML example

No text block when:

String html = "<html>\n" +
              "    <body>\n" +
              "        <p>Hello, world</p>\n" +
              "    </body>\n" +
              "</html>\n";
复制代码

Use the text block :

String html = """
              <html>
                  <body>
                      <p>Hello, world</p>
                  </body>
              </html>
              """;
复制代码

SQL example

No text block when:

String query = "SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`\n" +
               "WHERE `CITY` = 'INDIANAPOLIS'\n" +
               "ORDER BY `EMP_ID`, `LAST_NAME`;\n";
复制代码

Use the text block :

String query = """
               SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`
               WHERE `CITY` = 'INDIANAPOLIS'
               ORDER BY `EMP_ID`, `LAST_NAME`;
               """;
复制代码

description

Text block is a new word in the Java language. It can be used to represent any string, and provide a greater expressiveness and less complexity.

Text block consists of zero or more characters, start and end delimiters enclosed.

Is the start delimiter ( "" "), can be followed by zero or more spaces, and ultimately to the line terminator end of the three double-quote characters after the first character of the text block contents start delimiter line terminator Start.

Closing delimiter is represented by three double quote character, the contents of the text block to end before the end of the first double quote last character delimiter.

Text block content can be used directly "," may be used, but is not required.

Text block content may comprise direct line terminator. It allows the use of \ n in the text block, but not necessarily. For example, a block of text:

"""
line 1
line 2
line 3
"""
复制代码

It is equivalent to:

"line 1\nline 2\nline 3\n"
复制代码

Or a connection string:

"line 1\n" +
"line 2\n" +
"line 3\n"
复制代码

If the end of the string does not need to line terminator, the separator may be placed on the end of the last line. E.g:

"""
line 1
line 2
line 3"""
复制代码

It is equivalent to:

"line 1\nline 2\nline 3"
复制代码

Text blocks may represent the empty string, but not recommended, because it needs two lines of source code:

String empty = """
""";
复制代码

The following example is text block error form:

String a = """""";   // 开始分隔符后没有行终止符
String b = """ """;  // 开始分隔符后没有行终止符
String c = """
           ";        // 没有结束分隔符
String d = """
           abc \ def
           """;      // 含有未转义的反斜线(请参阅下面的转义处理)
复制代码

Compilation process

Text block is a constant expression of type String, just like strings. However, different from the string, Java compiler into three steps the processing contents of the text block:

  1. Line terminator content is converted into LF (\ u000A). The purpose of this conversion is to follow in the cross-platform mobile Java source code is the smallest surprise principle .
  2. In order to match the indentation Java source code, the contents of the extra spaces removed.
  3. Escape character interpretation content. As a final step which means developers can write an escape character, such as \ n, without being modified or deleted step before.

Minimum surprise principles: always do the least surprising thing

CONSTANT_String_info as processed contents entry in the constant pool in the class file is recorded, like string.

At runtime, the text block will be instantiated as an instance of String, just like strings. String text block derived from the Examples and Examples is derived from the character string indistinguishable. Two text blocks having the same content will refer to the same String instance, as the same character string.

The following sections discuss the process in more detail at compile time.

Line terminators

The content of the text block line terminator by the Java compiler to CR (\ u000D) and CRLF (\ u000D \ u000A) normalized LF (\ u000A). This ensures that the content of the text block on different platforms are equivalent.

Extra spaces

The following piece of code we use. To denote spaces in our code, and position of these spaces is redundant.

String html = """
..............<html>
..............    <body>
..............        <p>Hello, world</p>
..............    </body>
..............</html>
..............""";
复制代码

Extra spaces will appear at the end of each line, especially when you copied from elsewhere, more prone to this situation, such as the following code:

String html = """
..............<html>...
..............    <body>
..............        <p>Hello, world</p>....
..............    </body>.
..............</html>...
..............""";
复制代码

These extra spaces for programmers is invisible, but he is real, so if the compiler not treated, could lead to two blocks of text content programmers see is the same, but this two text blocks, but because the presence of such an extra space leads to the difference, such as the hash values ​​are not equal.

So the compiler at compile time delete these extra spaces.

Escape character

Allows developers to use \ n, \ f and \ r perpendicular to the format string, using \ b and \ t horizontal format. For example, the following code is legal:

String html = """
              <html>\r
                  <body>\r
                      <p>Hello, world</p>\r
                  </body>\r
              </html>\r
              """;
复制代码

Please note that the free use within the text block "is legal, even next to the start or end delimiter such as:

String story = """
    "When I use a word," Humpty Dumpty said,
    in rather a scornful tone, "it means just what I
    choose it to mean - neither more nor less."
    "The question is," said Alice, "whether you
    can make words mean so many different things."
    "The question is," said Humpty Dumpty,
    "which is to be master - that's all."""";
复制代码

However, three "sequence of characters need to be escaped at least one" to avoid mimic closing delimiter:

String code = 
    """
    String text = \"""
        A text block inside a text block
    \""";
    """;
复制代码

Text blocks are connected

Text blocks may be used anywhere in the string may be used. For example, text blocks and may be interconnected strings:

String code = "public void print(Object o) {" +
              """
                  System.out.println(Objects.toString(o));
              }
              """;
复制代码

However, the connection involving text blocks can become quite cumbersome. In the following text block basis:

String code = """
              public void print(Object o) {
                  System.out.println(Objects.toString(o));
              }
              """;
复制代码

Suppose we want to change the above Object to a variable, we can write:

String code = """
              public void print(""" + type + """
               o) {
                  System.out.println(Objects.toString(o));
              }
              """;
复制代码

The wording can be found readability is very poor, more simple alternative is to use String :: replace or String :: format, such as:

String code = """
              public void print($type o) {
                  System.out.println(Objects.toString(o));
              }
              """.replace("$type", type);
复制代码
String code = String.format("""
              public void print(%s o) {
                  System.out.println(Objects.toString(o));
              }
              """, type);
复制代码

Another approach is to use String :: formatted, this is a new method, such as:

String source = """
                public void print(%s object) {
                    System.out.println(Objects.toString(object));
                }
                """.formatted(type);
复制代码

Reference: openjdk.java.net/jeps/355

to sum up

This article was written before the JDK13 has not yet officially released, but also we want to make a sneak peek, hoping JDK13 able to publish as soon as possible, let us Javer can be used on a more convenient language. If you find this article allows you to acquire knowledge, can help forward, will share out knowledge. If you want the first time to learn more exciting content, please pay attention to micro-channel public number: 1:25

Guess you like

Origin juejin.im/post/5d061fa36fb9a07f03573944