展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

Jdk13新特性多⾏⽂本块

  • 旧的写法:在java代码⾥⾯编写多⾏源码带有特殊字符则需要转义,如HTML,sql等
# 案例1
public class Main{
	public static void main(String [] ags){
		String html = "<html>\n" +
                              " <body>\n" +
                              " <p>Hello, world</p>\n" +
                              " </body>\n" +
                              "</html>\n";
	}
}

# 案例2
public class Main{
	public static void main(String [] ags){
		String query = "SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`\n" +
                               "WHERE `CITY` = 'INDIANAPOLIS'\n" +
                               "ORDER BY `EMP_ID`, `LAST_NAME`;\n";
	}
}
  • 新的写法:原⽣字符串⽂字(raw string literals),它可以跨多⾏源码⽽不对转义字符进⾏转义
# 案例1
public class Main{
	public static void main(String [] ags){
		String html = """
                              <html>
                               <body>
                                <p>Hello, world</p>
                               </body>
                              </html>
                               """;
	}
}

# 案例2
public class Main{
	public static void main(String [] ags){
		String query = """
                               SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`
                               WHERE `CITY` = 'INDIANAPOLIS'
                               ORDER BY `EMP_ID`, `LAST_NAME`;
                               """;
	}
}
  • 在jshell中测试时
# 开启新版⽀持
jshell --enable-preview
  • 注意点:文本块不能写在第1行
# 错误写法
"""line 1
line 2
line 3
"""

# 正确写法1
"""
line 1
line 2
line 3"""

# 正确写法2
"""
line 1
line 2
line 3
"""
posted @ 2022-08-26 11:52  DogLeftover  阅读(14)  评论(0编辑  收藏  举报