Java 16 新特性 (EOL)
warning
生命周期结束时间(EOL): 2027/03
官方发布介绍页面:https://openjdk.org/projects/jdk/16/
1. 记录类
Records 在 JDK 16 中成为标准特性,提供了一种简洁的方式来定义不可变数据类。
public record Point(int x, int y) {}
Point point = new Point(1, 2);
System.out.println(point.x()); // 1
System.out.println(point.y()); // 2
2. instanceof 模式匹配
instanceof 模式匹配在 JDK 16 中成为标准特性,简化了类型检查和转换。
Object obj = "Hello, World!";
if (obj instanceof String s) {
System.out.println(s.toLowerCase()); // hello, world!
}
3. 密封类 (第二次预览)
Sealed Classes 允许类或接口限制哪些其他类或接口可以扩展或实现它们。
public abstract sealed class Shape permits Circle, Square {}
public final class Circle extends Shape {
// Implementation
}
public final class Square extends Shape {
// Implementation
}
4. 外部链接器 API (孵化器)
引入了外部链接器 API,允许 Java 程序调用本地代码。
5. 外部内存访问 API (第三次孵化器)
引入了外部内存访问 API,允许 Java 程序安全高效地访问外部内存。
6. 支持 Unix-Domain 套接字通道
引入了 Unix-Domain Socket Channels,允许在 Unix 域中进行套接字通信。
import java.io.IOException;
import java.net.UnixDomainSocketAddress;
import java.nio.channels.SocketChannel;
public class UnixDomainSocketExample {
public static void main(String[] args) throws IOException {
UnixDomainSocketAddress address = UnixDomainSocketAddress.of("/tmp/socket");
try (SocketChannel sc = SocketChannel.open(address)) {
// Use the socket channel
}
}
}
7. ZGC: 并发线程堆栈处理
ZGC 现在支持并发线程栈处理,进一步降低了暂停时间。
// 使用命令行参数来启用 ZGC
// -XX:+UseZGC
8. 强封装 JDK 内部元素
JDK 内部元素现在被强封装,无法通过反射访问。
9. Vector API (第一次孵化)
引入了 Vector API,允许在 Java 中进行矢量计算。
import jdk.incubator.vector.*;
public class VectorExample {
public static void main(String[] args) {
VectorSpecies<Integer> SPECIES = IntVector.SPECIES_256;
int[] a = {1, 2, 3, 4, 5, 6, 7, 8};
IntVector va = IntVector.fromArray(SPECIES, a, 0);
IntVector vb = va.add(1);
vb.intoArray(a, 0);
for (int i : a) {
System.out.println(i); // 2, 3, 4, 5, 6, 7, 8, 9
}
}
}