Java 17 LTS密封类
2026/1/15大约 3 分钟JavaJava版本特性LTS密封类JavaJava新特性LambdaStreamOptional模块化虚拟线程
概述
Java 17(2021年9月)是第三个 LTS 版本,也是目前推荐的生产环境版本。密封类正式发布,为 Java 的类型系统带来了重要增强。
密封类 (正式)
// 密封类定义
public sealed class Shape
permits Circle, Rectangle, Triangle {
public abstract double area();
}
// final 子类 - 不能再被继承
public final class Circle extends Shape {
private final double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double area() {
return Math.PI * radius * radius;
}
}
// sealed 子类 - 继续限制继承
public sealed class Rectangle extends Shape
permits Square {
protected final double width, height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double area() {
return width * height;
}
}
// final 子类
public final class Square extends Rectangle {
public Square(double side) {
super(side, side);
}
}
// non-sealed 子类 - 开放继承
public non-sealed class Triangle extends Shape {
private final double base, height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double area() {
return 0.5 * base * height;
}
}密封类与模式匹配
// 编译器知道所有可能的子类型
public double calculateArea(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle r -> r.width() * r.height();
case Triangle t -> 0.5 * t.base() * t.height();
// 不需要 default,因为已经穷尽所有情况
};
}密封接口
public sealed interface Vehicle
permits Car, Truck, Motorcycle {
String brand();
int wheels();
}
public record Car(String brand) implements Vehicle {
public int wheels() { return 4; }
}
public record Truck(String brand, int capacity) implements Vehicle {
public int wheels() { return 6; }
}
public record Motorcycle(String brand) implements Vehicle {
public int wheels() { return 2; }
}Switch 模式匹配 (预览)
// 类型模式
static String format(Object obj) {
return switch (obj) {
case Integer i -> "int: " + i;
case Long l -> "long: " + l;
case Double d -> "double: " + d;
case String s -> "String: " + s;
case null -> "null";
default -> "Unknown: " + obj;
};
}
// 守卫模式
static String classify(Object obj) {
return switch (obj) {
case Integer i when i > 0 -> "positive int";
case Integer i when i < 0 -> "negative int";
case Integer i -> "zero";
case String s when s.isEmpty() -> "empty string";
case String s -> "string: " + s;
default -> "other";
};
}
// Record 模式
record Point(int x, int y) {}
static String describe(Object obj) {
return switch (obj) {
case Point(int x, int y) when x == y -> "diagonal point";
case Point(int x, int y) -> "point at (" + x + ", " + y + ")";
default -> "not a point";
};
}增强的伪随机数生成器
// 新的随机数 API
RandomGenerator random = RandomGenerator.getDefault();
// 各种随机数生成器
RandomGenerator.of("L64X128MixRandom");
RandomGenerator.of("Xoshiro256PlusPlus");
// 可分割的随机数生成器(用于并行)
SplittableGenerator splittable = new SplittableRandom();
Stream<SplittableGenerator> splits = splittable.splits(10);
// 可跳跃的随机数生成器
JumpableGenerator jumpable = (JumpableGenerator) RandomGenerator.of("Xoroshiro128PlusPlus");
jumpable.jump(); // 跳跃到新状态
// 流式 API
random.ints(10, 0, 100).forEach(System.out::println);
random.doubles(5).forEach(System.out::println);上下文特定的反序列化过滤器
// 全局过滤器
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
"maxdepth=5;maxrefs=500;!com.example.dangerous.*"
);
ObjectInputFilter.Config.setSerialFilter(filter);
// 流特定过滤器
ObjectInputStream ois = new ObjectInputStream(inputStream);
ois.setObjectInputFilter(info -> {
if (info.serialClass() != null &&
info.serialClass().getName().startsWith("com.example.safe")) {
return ObjectInputFilter.Status.ALLOWED;
}
return ObjectInputFilter.Status.REJECTED;
});外部函数和内存 API (孵化)
// 分配本地内存
try (MemorySegment segment = MemorySegment.allocateNative(100)) {
MemoryAccess.setIntAtOffset(segment, 0, 42);
int value = MemoryAccess.getIntAtOffset(segment, 0);
}
// 映射文件
try (FileChannel channel = FileChannel.open(path)) {
MemorySegment mapped = channel.map(
FileChannel.MapMode.READ_ONLY, 0, channel.size(),
MemorySession.openImplicit()
);
}移除的特性
Applet API
// 已废弃并标记为移除
@Deprecated(since = "9", forRemoval = true)
public class Applet { }RMI Activation
RMI 激活机制被移除。
实验性 AOT 和 JIT 编译器
GraalVM 的 AOT 和 JIT 编译器从 JDK 中移除。
废弃的特性
Security Manager
// 已废弃,将在未来版本移除
@Deprecated(since = "17", forRemoval = true)
public class SecurityManager { }macOS 渲染管线
支持 Apple Metal API,提升图形性能。
强封装 JDK 内部
默认情况下,JDK 内部 API 被强封装。
# 如需访问内部 API
java --add-opens java.base/java.lang=ALL-UNNAMED MyApp
# 或在编译时
javac --add-exports java.base/sun.nio.ch=ALL-UNNAMED MyClass.java总结
| 特性 | 说明 |
|---|---|
| 密封类 | 正式发布,限制类继承 |
| Switch 模式匹配 | 预览,更强大的 switch |
| 随机数生成器 | 新的 RandomGenerator API |
| 反序列化过滤器 | 上下文特定的安全过滤 |
| 移除 Applet | 清理遗留 API |
| 强封装 | JDK 内部 API 默认封装 |
Java 17 作为 LTS 版本,是从 Java 8 或 Java 11 升级的理想目标。密封类的正式发布为领域建模提供了更精确的类型表达能力。
