概述

JDK 17 是继 JDK 8 之后最重要的 LTS 版本,支持至 2029 年。
Spring 6.x / Spring Boot 3.x 最低要求 Java 17。

Records关键字

一个新的关键字,和class、enum一个级别。是不可变数据载体的终极方案,类似于Lombok功能。
特别的是声明的时候就带有参数

解决的问题:传统 POJO/DTO/VO 需要编写私有字段、构造器、getter、equals()、hashCode()、toString() 等大量样板代码。

核心用法:

1
2
3
4
5
6
7
8
// 一行代码定义一个不可变数据类
public record Point(int x, int y) { }

// 使用
Point p = new Point(10, 20);
System.out.println(p.x()); // 10(注意:是 x(),不是 getX())
System.out.println(p); // Point[x=10, y=20]
System.out.println(p.equals(new Point(10, 20))); // true

自动生成的能力:

  • 全参构造器
  • 与字段同名的访问器(不是 getXxx 风格)
  • 基于所有字段的 equals() 和 hashCode()
  • toString() 输出类名和字段键值对

强制不可变性:所有字段默认 private final,不允许声明非 final 实例字段,隐式继承 java.lang.Record,不能再继承其他类。

实用场景:DTO/VO、事件对象、坐标/元组等纯数据载体,代码量可减少 70% 以上。

Sealed关键字

解决的问题:传统继承中,final 完全禁止继承,默认开放又无法限制子类范围,缺乏中间粒度。

核心用法:

1
2
3
4
5
6
7
public sealed interface Shape permits Circle, Square, Rectangle {
double area();
}

public final class Circle implements Shape { /*...*/ } // final:不能再被继承
public non-sealed class Square implements Shape { /*...*/ } // 允许继续扩展
public sealed class Rectangle implements Shape permits ColoredRectangle { /*...*/ } // sealed:继续限制,只允许 ColoredRectangle 继承

关键规则:

  • 子类必须声明为 final、sealed 或 non-sealed 三者之一
  • 所有允许的子类必须在同一模块或包中
  • 使用 permits 关键字明确列出所有合法子类

instanceof

解决的问题:传统的 if (obj instanceof Type) { Type t = (Type) obj; ... } 存在重复的类型书写和强制转换风险。

1
2
3
4
5
6
7
8
9
10
// 传统写法
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.length());
}

// JDK 17 写法:类型判断 + 变量绑定 + 自动转换,一步完成
if (obj instanceof String s) {
System.out.println(s.length()); // 直接使用 s
}

将类型检查、强制转换、变量声明合并为单个表达式,消除了重复代码和错误转换的风险。