Java 14-15 Records与密封类
2026/1/15大约 3 分钟JavaJava版本特性Records密封类JavaJava新特性LambdaStreamOptional模块化虚拟线程
Java 14 (2020年3月)
Switch 表达式 (正式)
// 正式成为标准特性
String result = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> "6 letters";
case TUESDAY -> "7 letters";
case THURSDAY, SATURDAY -> "8 letters";
case WEDNESDAY -> "9 letters";
};Records (预览)
Records 是不可变数据类的简洁写法。
// 传统 POJO
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int x() { return x; }
public int y() { return y; }
@Override
public boolean equals(Object o) { ... }
@Override
public int hashCode() { ... }
@Override
public String toString() { ... }
}
// Record
public record Point(int x, int y) {}
// 使用
Point p = new Point(10, 20);
System.out.println(p.x()); // 10
System.out.println(p.y()); // 20
System.out.println(p); // Point[x=10, y=20]Record 特性
// 自定义构造器
public record Person(String name, int age) {
// 紧凑构造器 - 用于验证
public Person {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
name = name.trim(); // 可以修改参数
}
// 自定义构造器
public Person(String name) {
this(name, 0);
}
}
// 自定义方法
public record Rectangle(int width, int height) {
public int area() {
return width * height;
}
public static Rectangle square(int side) {
return new Rectangle(side, side);
}
}
// 实现接口
public record Point(int x, int y) implements Comparable<Point> {
@Override
public int compareTo(Point other) {
return Integer.compare(this.x, other.x);
}
}instanceof 模式匹配 (预览)
// 传统方式
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.length());
}
// 模式匹配
if (obj instanceof String s) {
System.out.println(s.length());
}
// 可以在条件中使用
if (obj instanceof String s && s.length() > 5) {
System.out.println(s.toUpperCase());
}有用的 NullPointerException
// 之前
a.b.c.d = 10;
// NullPointerException: null
// Java 14
a.b.c.d = 10;
// NullPointerException: Cannot read field "c" because "a.b" is null启用方式:
java -XX:+ShowCodeDetailsInExceptionMessages MyApp文本块 (第二次预览)
新增转义序列:
String text = """
Line 1
Line 2 \
continues here
Line 3\s\s
""";
// \ - 行尾续行
// \s - 保留空格Java 15 (2020年9月)
密封类 (预览)
限制哪些类可以继承或实现。
// 密封类
public sealed class Shape
permits Circle, Rectangle, Triangle {
}
// 子类必须是 final、sealed 或 non-sealed
public final class Circle extends Shape {
private final double radius;
public Circle(double radius) { this.radius = radius; }
}
public sealed class Rectangle extends Shape
permits Square {
// ...
}
public final class Square extends Rectangle {
// ...
}
// non-sealed 允许任意继承
public non-sealed class Triangle extends Shape {
// ...
}密封接口
public sealed interface Vehicle
permits Car, Truck, Motorcycle {
}
public final class Car implements Vehicle {}
public final class Truck implements Vehicle {}
public non-sealed class Motorcycle implements Vehicle {}Records (第二次预览)
// 本地 Record
public void process() {
record TempResult(int value, String message) {}
TempResult result = new TempResult(42, "Success");
System.out.println(result);
}
// Record 可以实现接口
public record Point(int x, int y) implements Serializable {}instanceof 模式匹配 (第二次预览)
// 更复杂的模式
if (obj instanceof String s && !s.isEmpty()) {
System.out.println(s.toUpperCase());
}
// 在 switch 中使用(预览)
static String format(Object obj) {
return switch (obj) {
case Integer i -> "int: " + i;
case Long l -> "long: " + l;
case String s -> "String: " + s;
default -> "Unknown";
};
}文本块 (正式)
// 正式成为标准特性
String json = """
{
"name": "John",
"age": 30
}
""";隐藏类 (Hidden Classes)
用于框架动态生成类,不能被其他类直接使用。
// 主要用于框架开发
Lookup lookup = MethodHandles.lookup();
ClassDesc cd = ClassDesc.of("com.example.Generated");
byte[] classBytes = generateClassBytes();
Class<?> hiddenClass = lookup.defineHiddenClass(
classBytes, true, ClassOption.NESTMATE).lookupClass();ZGC 和 Shenandoah 正式发布
# ZGC
java -XX:+UseZGC MyApp
# Shenandoah
java -XX:+UseShenandoahGC MyApp移除 Nashorn JavaScript 引擎
Nashorn 被移除,推荐使用 GraalVM。
移除 Solaris 和 SPARC 支持
总结
| 版本 | 主要特性 |
|---|---|
| Java 14 | Switch 表达式(正式)、Records(预览)、instanceof 模式匹配(预览)、有用的 NPE |
| Java 15 | 密封类(预览)、文本块(正式)、ZGC/Shenandoah(正式) |
Java 14 和 15 引入了 Records 和密封类这两个重要特性,为 Java 的数据建模提供了更简洁的方式。
