JAVA9-17特性梳理

9

jshell

一个可以直接执行JAVA代码的命令行shell

接口私有方法

可以在接口中声明private修饰的方法

try with resource更新

支持处理在语句块外部创建的资源

FileInputStream fis = new FileInputStream("in.txt");
FileOutputStream fos = new FileOutputStream("out.txt");
try (fis; fos) {
} catch (IOException e) {
	e.printStackTrace();
}

禁用下划线变量

字符串实现更新

char数组改为使用byte数组

模块化

stream更新

增加方法takeWhile dropWhile ofNullable iterate

新增HttpClient

10

局部变量类型推断

可以使用var声明局部变量,编译器会自动推断变量类型

11

直接运行JAVA文件

String新增方法

  1. 去除首尾空白strip,去除头部空白stripLeading,去除尾部空白stripTrailing
  2. 判断空白isBlank。长度0,或全是空格,制表符等空白字符
  3. 重复打印repeat
  4. 拆行lines

lambda表达式参数类型推断

可以使用var生命表达式参数

12

13

文本块

可以使用三重双引号直接包裹多行文本

String s = """
            Hello
            World
           """;

14

switch更新

定版发布了12,13中预览更新

  1. 避免过多break
switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> System.out.println(6);
    case TUESDAY                -> System.out.println(7);
    case THURSDAY, SATURDAY     -> System.out.println(8);
    case WEDNESDAY              -> System.out.println(9);
    default                     -> System.out.println(0);
}
  1. 支持返回值
int numLetters = switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> 6;
    case TUESDAY                -> 7;
    case THURSDAY, SATURDAY     -> 8;
    case WEDNESDAY              -> 9;
    default                     -> 0;
};

15

TreeMap新增方法

putIfAbsent
computeIfAbsent
computeIfPresent
compute
merge

16

关键字record

用于定义POJO类,不必书写类实现
Person.java

public record Person(String name, Integer age){}

时间段格式化

新增模板字符B,用于获取“午夜”,“凌晨”,“清晨”,“上午”,“中午”,“下午”,“晚上”这样格式的信息

System.out.println(DateTimeFormatter.ofPattern("B").format(LocalDateTime.now()));

instanceof

// 之前
if (obj instanceof String) {
    String s = (String) obj;
    ...
}
// 之后
if (obj instanceof String s) {
    // 可直接使用变量s
    ...
}

jpackage打包工具

17

sealed关键字

用于限制接口或类只能被指定的接口或类实现或继承

posted on 2022-04-11 22:37  路过君  阅读(37)  评论(0编辑  收藏  举报

导航