Java 22-25 最新版本
2026/1/15大约 4 分钟JavaJava版本特性JavaJava新特性LambdaStreamOptional模块化虚拟线程
Java 22 (2024年3月)
未命名变量和模式 (正式)
// 未命名变量
try {
riskyOperation();
} catch (Exception _) {
log.error("Operation failed");
}
// Lambda 中
map.forEach((_, v) -> process(v));
// 增强 for 循环
int count = 0;
for (var _ : collection) {
count++;
}
// 未命名模式
if (obj instanceof Point(int x, _)) {
System.out.println("x = " + x);
}
switch (shape) {
case Circle(var r) -> System.out.println("Circle");
case Rectangle(_, var h) -> System.out.println("Height: " + h);
}外部函数和内存 API (正式)
// 正式发布,替代 JNI
try (Arena arena = Arena.ofConfined()) {
// 分配本地内存
MemorySegment segment = arena.allocate(ValueLayout.JAVA_INT, 100);
// 调用本地函数
Linker linker = Linker.nativeLinker();
MethodHandle strlen = linker.downcallHandle(
linker.defaultLookup().find("strlen").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS)
);
MemorySegment str = arena.allocateFrom("Hello, World!");
long len = (long) strlen.invoke(str);
System.out.println("Length: " + len);
}语句前的 super()
// 在调用 super() 之前可以执行语句
class Sub extends Base {
Sub(int value) {
// 可以在 super() 之前执行验证
if (value < 0) {
throw new IllegalArgumentException("Value must be non-negative");
}
super(value);
}
}
// 可以计算参数
class Rectangle extends Shape {
Rectangle(int width, int height) {
int area = width * height; // 先计算
super(area); // 再调用父类构造器
}
}字符串模板 (第二次预览)
// 改进的字符串模板
String name = "World";
int year = 2024;
// STR 处理器
String greeting = STR."Hello, \{name}! Welcome to \{year}.";
// 多行模板
String html = STR."""
<html>
<body>
<h1>Hello, \{name}!</h1>
<p>Year: \{year}</p>
</body>
</html>
""";
// RAW 处理器 - 获取原始模板
StringTemplate template = RAW."Hello, \{name}!";
List<String> fragments = template.fragments();
List<Object> values = template.values();Stream Gatherers (预览)
自定义中间操作。
// 内置 Gatherer
// windowFixed - 固定大小窗口
Stream.of(1, 2, 3, 4, 5, 6)
.gather(Gatherers.windowFixed(2))
.forEach(System.out::println);
// [1, 2], [3, 4], [5, 6]
// windowSliding - 滑动窗口
Stream.of(1, 2, 3, 4, 5)
.gather(Gatherers.windowSliding(3))
.forEach(System.out::println);
// [1, 2, 3], [2, 3, 4], [3, 4, 5]
// fold - 有状态的归约
Stream.of(1, 2, 3, 4, 5)
.gather(Gatherers.fold(() -> 0, Integer::sum))
.forEach(System.out::println);
// 15
// scan - 累积操作
Stream.of(1, 2, 3, 4, 5)
.gather(Gatherers.scan(() -> 0, Integer::sum))
.forEach(System.out::println);
// 1, 3, 6, 10, 15类文件 API (预览)
// 读取类文件
ClassModel classModel = ClassFile.of().parse(bytes);
// 遍历类成员
classModel.methods().forEach(method -> {
System.out.println(method.methodName().stringValue());
});
// 生成类文件
byte[] bytes = ClassFile.of().build(
ClassDesc.of("com.example.Generated"),
classBuilder -> {
classBuilder.withMethod(
"hello",
MethodTypeDesc.of(CD_void),
ClassFile.ACC_PUBLIC | ClassFile.ACC_STATIC,
methodBuilder -> {
methodBuilder.withCode(codeBuilder -> {
codeBuilder.getstatic(CD_System, "out", CD_PrintStream)
.ldc("Hello, World!")
.invokevirtual(CD_PrintStream, "println",
MethodTypeDesc.of(CD_void, CD_String))
.return_();
});
}
);
}
);Java 23 (2024年9月)
原始类型模式 (预览)
// 在模式匹配中使用原始类型
switch (obj) {
case int i -> System.out.println("int: " + i);
case long l -> System.out.println("long: " + l);
case double d -> System.out.println("double: " + d);
case Integer i -> System.out.println("Integer: " + i);
default -> System.out.println("other");
}
// instanceof 中使用
if (obj instanceof int i) {
System.out.println("Primitive int: " + i);
}模块导入声明 (预览)
// 导入整个模块的所有公共类型
import module java.base;
import module java.sql;
// 使用时无需单独导入
public class Example {
public void demo() {
List<String> list = new ArrayList<>(); // 无需 import java.util.*
Connection conn = ...; // 无需 import java.sql.*
}
}Markdown 文档注释
/**
* # 方法说明
*
* 这是一个示例方法。
*
* ## 参数
* - `name` - 用户名称
* - `age` - 用户年龄
*
* ## 返回值
* 返回格式化的字符串
*
* ## 示例
* ```java
* String result = format("Alice", 25);
* ```
*
* @param name 用户名称
* @param age 用户年龄
* @return 格式化的字符串
*/
public String format(String name, int age) {
return STR."\{name} is \{age} years old";
}灵活的构造器体 (第二次预览)
class Derived extends Base {
private final int computed;
Derived(int value) {
// 在 super() 之前初始化字段
this.computed = value * 2;
// 验证
if (computed < 0) {
throw new IllegalArgumentException();
}
// 调用父类构造器
super(computed);
}
}ZGC 分代模式 (默认)
# ZGC 现在默认使用分代模式
java -XX:+UseZGC MyApp
# 显式使用分代 ZGC
java -XX:+UseZGC -XX:+ZGenerational MyApp
# 使用非分代 ZGC
java -XX:+UseZGC -XX:-ZGenerational MyAppJava 24 (2025年3月)
字符串模板 (移除)
字符串模板特性被移除,将重新设计。
Stream Gatherers (第二次预览)
// 更多内置 Gatherer
Stream.of(1, 2, 3, 4, 5)
.gather(Gatherers.mapConcurrent(4, this::process))
.toList();类文件 API (第二次预览)
API 进一步完善。
结构化并发 (第三次预览)
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
var user = scope.fork(() -> fetchUser(id));
var orders = scope.fork(() -> fetchOrders(id));
scope.join();
scope.throwIfFailed();
return new UserData(user.get(), orders.get());
}作用域值 (第二次预览)
static final ScopedValue<User> CURRENT_USER = ScopedValue.newInstance();
void handleRequest(User user) {
ScopedValue.runWhere(CURRENT_USER, user, () -> {
processRequest();
});
}
void processRequest() {
User user = CURRENT_USER.get();
// 使用当前用户
}Java 25 (2025年9月) - 预计 LTS
预期特性
- 字符串模板 - 重新设计后发布
- 结构化并发 - 正式发布
- 作用域值 - 正式发布
- Stream Gatherers - 正式发布
- 原始类型模式 - 可能正式发布
- 值类型 - 可能预览(Project Valhalla)
值类型 (预期)
// 值类型 - 无身份的对象
value class Point {
int x;
int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
}
// 特点:
// - 没有对象头,内存占用更小
// - 可以内联存储
// - 不能为 null
// - 不能使用 synchronized
// - 不能使用 == 比较身份版本选择建议
| 场景 | 推荐版本 |
|---|---|
| 新项目 | Java 21 (LTS) |
| 保守升级 | Java 17 (LTS) |
| 尝鲜新特性 | Java 23/24 |
| 遗留系统 | Java 11 (LTS) |
| 等待下一个 LTS | Java 25 (2025年9月) |
总结
| 版本 | 主要特性 |
|---|---|
| Java 22 | 未命名变量(正式)、外部函数和内存 API(正式)、Stream Gatherers(预览) |
| Java 23 | 原始类型模式(预览)、模块导入(预览)、Markdown 文档注释 |
| Java 24 | Stream Gatherers(第二次预览)、结构化并发(第三次预览) |
| Java 25 | 预计 LTS,多个预览特性正式发布 |
Java 持续以每6个月一个版本的节奏演进,建议生产环境使用 LTS 版本(Java 21),同时关注新版本的预览特性,为未来升级做好准备。
