01.3、Java 21核心新特性
Java 21 核心新特性
Java 21 引入了许多重要的新特性,这些特性不仅提升了开发效率,还改善了代码的可读性和性能。理解这些新特性,是掌握 Java 21 的关键。
本节将学习:Record 类型、Pattern Matching(模式匹配)、Sealed Classes(密封类)、Virtual Threads(虚拟线程),以及 String Templates(字符串模板)。
Record 类型
什么是 Record?
Record 是 Java 14 引入的特性,在 Java 21 中已经稳定。Record 是一种特殊的数据类,用于简化不可变数据对象的定义。
Record 示例
// 传统方式 public class User { private final String name; private final int age; public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return age == user.age && Objects.equals(name, user.name); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public String toString() { return "User{name='" + name + "', age=" + age + "}"; } } // Record 方式 public record User(String name, int age) {}
优势:
- 代码量减少 70% 以上
- 自动生成所有必要的方法
- 不可变对象,线程安全
- 代码更简洁易读
Record 的高级特性
// 自定义构造函数 public record User(String name, int age) { public User { if (age < 0) { throw new IllegalArgumentException("Age must be positive"); } } // 自定义方法 public boolean isAdult() { return age >= 18; } }
Pattern Matching(模式匹配)
什么是 Pattern Matching?
Pattern Matching 是 Java 16 引入的特性,在 Java 21 中得到了增强。它允许在 switch 表达式和 instanceof 中使用模式匹配,简化条件判断。
instanceof 模式匹配
// Java 8 方式 if (obj instanceof String) { String str = (String) obj; System.out.println(str.length()); } // Java 21 方式 if (obj instanceof String str) { System.out.println(str.length()); }
优势: 自动类型转换,无需显式强制转换。
switch 模式匹配
// Java 8 方式 public String process(Object obj) { if (obj instanceof String) { return "String: " + obj; } else if (obj instanceof Integer) { return "Integer: " + obj; } else if (obj instanceof Double) { return "Double: " + obj; } else { return "Unknown"; } } // Java 21 方式 public String process(Object obj) { return switch (obj) { case String str -> "String: " + str; case Integer i -> "Integer: " + i; case Double d -> "Double: " + d; default -> "Unknown"; }; }
优势: 代码更简洁,类型安全。
Record 模式匹配
public record Point(int x, int y) {} public String process(Point p) { return switch (p) { case Point(int x, int y) when x == y -> "On diagonal"; case Point(int x, int y) when x > y -> "Right of diagonal"; default -> "Left of diagonal"; }; }
Sealed Classes(密封类)
什么是 Sealed Classes?
Sealed Classes 是 Java 17 引入的特性,允许限制哪些类可以继承或实现某个类或接口。
Sealed Classes 示例
// 定义密封类 public sealed class Shape permits Circle, Rectangle, Triangle { } // 允许的子类 public final class Circle extends Shape { private final double radius; public Circle(double radius) { this.radius = radius; } } public final class Rectangle extends Shape { private final double width, height; public Rectangle(double width, double height) { this.width = width; this.height = height; } } public final class Triangle extends Shape { private final double a, b, c; public Triangle(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } }
优势:
- 类型安全:编译时检查所有子类
- 模式匹配友好:配合 switch 使用,编译器可以检查是否覆盖所有情况
- API 设计:明确 API 的扩展点
与 Pattern Matching 结合
public double area(Shape shape) { return switch (shape) { case Circle c -> Math.PI * c.radius() * c.radius(); case Rectangle r -> r.width() * r.height(); case Triangle t -> { double s = (t.a() + t.b() + t.c()) / 2; yield Math.sqrt(s * (s - t.a()) * (s - t.b()) * (s - t.c())); } }; }
编译器会检查是否覆盖了所有可能的子类。
Virtual Threads(虚拟线程)
什么是 Virtual Threads?
Virtual Threads 是 Java 21 最重要的新特性之一。它们是轻量级线程,由 JVM 管理,而不是操作系统线程。
Virtual Threads 特点
特点:
- 轻量级:内存占用仅几 KB
- 高并发:可以创建数百万个虚拟线程
- 简单 API:与现有线程 API 完全兼容
Virtual Threads 示例
// 传统方式(平台线程) try (var executor = Executors.newFixedThreadPool(100)) { for (int i = 0; i < 10000; i++) { executor.submit(() -> { // 任务逻辑 try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); } } // Virtual Threads 方式 try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { for (int i = 0; i < 10000; i++) { executor.submit(() -> { // 任务逻辑 try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); } }
优势:
- 可以创建大量线程而不会消耗大量系统资源
- 适合 I/O 密集型任务
- 代码无需修改,只需更换 Executor
性能对比
| 指标 | 平台线程 | 虚拟线程 | 提升 |
|---|---|---|---|
| 内存占用 | ~1MB/线程 | ~几KB/线程 | 100-1000倍 |
| 最大线程数 | ~1000-10000 | 数百万 | 100-1000倍 |
| 创建速度 | 慢 | 快 | 10-100倍 |
String Templates(字符串模板)
什么是 String Templates?
String Templates 是 Java 21 的预览特性,提供了一种更简洁的字符串插值方式。
String Templates 示例
// 传统方式 String name = "John"; int age = 30; String message = "Hello, " + name + "! You are " + age + " years old."; // String Templates 方式(预览特性) String message = STR."Hello, \{name}! You are \{age} years old.";
优势:
- 代码更简洁
- 类型安全
- 性能更好(编译时处理)
多行字符串模板
String html = STR.""" <html> <body> <h1>Hello, \{name}!</h1> <p>You are \{age} years old.</p> </body> </html> """;
官方资源
- Java 21 新特性:https://docs.oracle.com/en/java/javase/21/
- Record 文档:https://docs.oracle.com/en/java/javase/21/language/records.html
- Pattern Matching 文档:https://docs.oracle.com/en/java/javase/21/language/pattern-matching.html
- Virtual Threads 文档:https://docs.oracle.com/en/java/javase/21/core/virtual-threads.html
本节小结
在本节中,我们学习了:
第一个是 Record 类型。 简化数据类定义,代码量减少 70% 以上。
第二个是 Pattern Matching。 简化类型检查和条件判断,代码更简洁。
第三个是 Sealed Classes。 限制类的继承,提供类型安全和模式匹配友好。
第四个是 Virtual Threads。 轻量级线程,可以创建数百万个,适合高并发场景。
第五个是 String Templates。 更简洁的字符串插值方式,类型安全。
这就是 Java 21 的核心新特性。掌握这些特性,可以大幅提升开发效率和代码质量。
在下一节,我们将从企业级应用的角度,分析选择 Java 21 的考量因素。