sealed class Shape permits Circle, Rectangle {
// 基类代码
}
final class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
}
non-sealed class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
}
特性说明:
sealed 限制可以继承的类。
permits 明确指定子类。
子类必须是 final、sealed 或 non-seale
2. Switch 模式匹配(预览功能)
Switch 表达式支持基于模式的匹配,让代码更简洁。
代码示例
java复制代码
public class PatternMatchingDemo {
public static String formatShape(Object shape) {
return switch (shape) {
case Circle c -> "Circle with radius: " + c.radius;
case Rectangle r -> "Rectangle with length: " + r.length + ", width: " + r.width;
default -> "Unknown shape";
};
}
public static void main(String[] args) {
Shape shape = new Circle(5.0);
System.out.println(formatShape(shape));
}
}
import java.util.stream.Stream;
public class StreamApiDemo {
public static void main(String[] args) {
var list = Stream.of("Java", "Python", "C++")
.map(String::toUpperCase)
.toList(); // 直接转换为列表
System.out.println(list);
}
}
特性说明:
toList() 方法返回一个不可变列表。
简化了流到集合的转换。
5. RandomGenerator API
新的 RandomGenerator API 提供了更多的随机数生成器,实现更高效和多样的生成。
代码示例
java复制代码
import java.util.random.RandomGenerator;
public class RandomGeneratorDemo {
public static void main(String[] args) {
RandomGenerator random = RandomGenerator.of("L64X128MixRandom");
for (int i = 0; i < 5; i++) {
System.out.println(random.nextInt(100)); // 生成 0 到 99 的随机数
}
}
}
特性说明:
支持多种算法,提供更灵活的选择。
适合科学计算和并行环境。
6. ZGC 与 G1 GC 的增强
Java 17 优化了 ZGC(低延迟垃圾回收器)和 G1 GC 的性能,使得内存管理更加高效。
ZGC 示例
java复制代码
// JVM 参数配置
// -XX:+UseZGC -Xmx2g -Xms2g
public class ZGCDemo {
public static void main(String[] args) {
System.out.println("Using ZGC in Java 17");
// 模拟大内存分配和释放
}
}
特性说明:
ZGC 的暂停时间可以保持在 10 毫秒以内。
适合低延迟、高吞吐量的应用场景。
7. 废弃和移除
Applet API 移除: Applet 技术因过时和安全问题被移除。
强制 UTF-8: Java 17 中,默认字符集改为 UTF-8,提升了国际化支持。
UTF-8 示例
java复制代码
public class UTF8Demo {
public static void main(String[] args) {
String text = "你好,世界!"; // UTF-8 字符
System.out.println(text);
}
}