JAVA17新特性
目录
Java 17 在 2021 年 9 月 14 日正式发布,是一个长期支持(LTS)版本。 作为一个长期支持版本(LTS),带来了许多重要的特性和更新。本文将介绍这些新的特性、同时也提供Java17的下载。
java17 新特性
sealed class
封闭类允许类或接口限制哪些其他类或接口可以继承或实现它们。这增强了Java的类型系统,使得创建更可预测和安全的类型层次结构成为可能。
示例:
// 声明一个密封类
public sealed class Shape
permits Circle, Rectangle, Square {
// 定义 Shape 的属性和方法
}
// 圆形类,继承自 Shape
final class Circle extends Shape {
private double radius;
// 构造函数和方法
}
// 矩形类,继承自 Shape
final class Rectangle extends Shape {
private double length;
private double width;
// 构造函数和方法
}
// 正方形类,继承自 Shape
final class Square extends Shape {
private double side;
// 构造函数和方法
}
public class Main {
public static void main(String[] args) {
// 使用密封类
Shape shape = new Circle();
// ... 进行操作
}
}
pattern matching for switch
这个特性扩展了switch语句和表达式,使其能够使用模式匹配,这使得代码更加简洁和灵活。 以下是一个使用Java17中模式匹配forswitch 特性的示例: 假设我们有一个基类Shape和几个子类Circle,Rectangle, Square,我们想根据形状类型来执行不同的操作。
首先,定义这些类:
abstract class Shape {}
final class Circle extends Shape {
final double radius;
Circle(double radius) { this.radius = radius; }
}
final class Rectangle extends Shape {
final double length, width;
Rectangle(double length, double width) { this.length = length; this.width = width; }
}
final class Square extends Shape {
final double side;
Square(double side) { this.side = side; }
}
然后,我们使用模式匹配 in switch 来处理这些不同的形状:
public class PatternMatchingDemo {
public static void main(String[] args) {
Shape shape = new Circle(10);
String result = switch (shape) {
case Circle c -> "Circle with radius: " + c.radius;
case Rectangle r -> "Rectangle with length: " + r.length + " and width: " + r.width;
case Square s -> "Square with side: " + s.side;
default -> "Unknown shape";
};
System.out.println(result);
}
}
在这个示例中,switch语句使用模式匹配来检查shape变量的实际类型。对于每一种类型的Shape(例如 Circle, Rectangle, Square),我们定义了一个不同的case,用于提取特定类型的详细信息并生成一个相应的字符串描述。
strong encapsulation of jdk internals
Java17继续加强对JDK内部API的封装,以防止它们被外部应用程序错误地使用,从而提高安全性和可维护性。
new macos rending pipeline
Java17引入了新的基于Apple Metal API的MacOS渲染管线,以提高MacOS上的性能和用户体验。
- 移除和弃用功能 Java17移除了一些旧的特性,如AppletAPI,并标记了一些功能为弃用,如Security Manager等
JAVA17下载地址
Product / File Description | File Size | Download Link |
---|---|---|
Linux Arm 64 Compressed Archive | 172.37 MB | Download (sha256) |
Linux Arm 64 RPM Package | 172.62 MB | Download (sha256) |
Linux x64 Compressed Archive | 174.01 MB | Download (sha256) |
Linux x64 Debian Package | 149.40 MB | Download (sha256) |
Linux x64 RPM Package | 173.73 MB | Download (sha256) |
macOS Arm 64 Compressed Archive | 168.18 MB | Download (sha256) |
macOS Arm 64 DMG Installer | 167.60 MB | Download (sha256) |
macOS x64 Compressed Archive | 170.62 MB | Download (sha256) |
macOS x64 DMG Installer | 170.03 MB | Download (sha256) |
Windows x64 Compressed Archive | 172.42 MB | Download (sha256) |
Windows x64 Installer | 153.51 MB | Download (sha256) |
Windows x64 MSI Installer | 152.30 MB | Download (sha256) |