Skip to content

JDK 21 其他特性

JDK 21 除了主要特性外还有其他重要更新。

Record Patterns

记录类型模式匹配:

java
record Point(int x, int y) {}

if (p instanceof Point(int x, int y)) {
    System.out.println("x=" + x + ", y=" + y);
}

Unnamed Patterns

未命名模式:

java
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Value: " + numbers[i]);
}

String Templates(预览)

java
String name = "World";
String template = STR."Hello \{name}!";

Scoped Values(预览)

java
ScopedValue<String> shared = ScopedValue.newInstance();

Foreign Function & Memory API

调用本地方法:

java
try (MemorySession session = MemorySession.open()) {
    Linker linker = Linker.nativeLinker();
    MemoryAddress sum = linker.defaultLookup().find("sum").orElseThrow();
    MethodHandle mh = linker.downcallHandle(sum, FunctionDescriptor.of(
        ValueLayout.JAVA_INT,
        ValueLayout.JAVA_INT,
        ValueLayout.JAVA_INT
    ));
    int result = (int) mh.invokeExact(10, 20);
}

小结

JDK 21 的其他特性:

  • Record Patterns:数据解构
  • Unnamed Patterns:简化代码
  • String Templates:字符串插值
  • Scoped Values:线程间数据共享
  • Foreign Function API:本地互操作

JDK 21 是 LTS 版本,推荐在新项目中使用。

基于 VitePress 构建