概述

Java 17 作为长期支持版本(LTS),引入了多项重要的语言特性改进,主要围绕模式匹配、简洁性和安全性进行增强。

一、switch增强

1. case不需要break

    switch (1) {
        case 1 -> System.out.println("1");
        case 2 -> System.out.println("2");
        default -> System.out.println("default");
    }
    // 输出结果: 1

2. switch语句可以有return

    int sum = switch (1) {
        case 1 -> 1;
        case 2 -> 2;
        default -> 0;
    };
    System.out.println(sum);
    // 输出结果: 1

/

3. case 可以匹配多个值

    int sum = switch (1) {
        case 1,2 -> 2;
        default -> 0;
    };
    System.out.println(sum);
    // 输出结果: 2

4. switch 支持对对象类型进行匹配(模式匹配)

    // 带条件匹配
    Object obj = 42;

    String result = switch (obj) {
        case String s when s.length() > 5 -> "长字符串: " + s;
        case String s -> "短字符串: " + s;
        case Integer i when i > 100 -> "大整数: " + i;
        case Integer i -> "小整数: " + i;
        default -> "其他类型";
    };

    System.out.println(result);
    // 输出结果: 小整数: 42

二、字符串拼接

1. 多行字符串处理方式

String msg = """
                     当前会话在SSO-Server端尚未登录,请先访问
                     <a href='/sso/doLogin?name=sa&pwd=123456' target='_blank'> doLogin登录 </a>

                     进行登录之后,刷新页面开始授权
                     """;

2. instanceof增强

对instanceof 对象类型 判断后 不需要进行强转 可直接使用当前类型

Java 17 之前的写法

Object obj = "Hello World";

if (obj instanceof String) {
    String str = (String) obj;  // 需要强制类型转换
    System.out.println("字符串长度: " + str.length());
}

Java 17 增强后的写法

Object obj = "Hello World";

// 在 instanceof 判断时直接声明变量,无需强制类型转换
if (obj instanceof String str) {
    System.out.println("字符串长度: " + str.length());
    // str 可以直接使用,类型为 String
}

// 也可以在条件表达式中使用
if (obj instanceof String str && str.length() > 5) {
    System.out.println("长字符串: " + str);
}

三、密封类(Sealed Classes)

限制Animal只能被Dog和Cat类继承

public abstract sealed class Animal permits Dog, Cat {
    
}

子类继承必须使用final或者non-sealed关键字

final表示子类Cat 无法再继承

public final class Cat extends Animal {
    
}

non-sealed表示Dog类还可以被子类继承

public non-sealed class Dog extends Animal {
    
}

四、Record类

类似lombok的属性只读对象

一旦创建一个Record类 是不允许修改值的

两个属性值一样的Record类,equlas方法是为True,因为Record重写了hashCode和equlas方法

public record Test(Long userId, String userName) {
}

字节码文件

public record Test(Long userId, String userName) {
    public Test(Long userId, String userName) {
        this.userId = userId;
        this.userName = userName;
    }

    public Long userId() {
        return this.userId;
    }

    public String userName() {
        return this.userName;
    }
}

1. 优化空指针异常

在链式调用中 能打印出具体是哪个对象为null

2. ZGC垃圾收集器

默认的垃圾回收器还是G1

3. 开启ZGC

-XX:+UseZGC