在本教程中,我们将深入探讨最新的 Java 版本,Java 22,它现在已经普遍可用。
2. Java 语言更新
让我们来谈谈作为这个版本一部分的 Java 语言的所有新变化。
2.1. 未命名变量和模式 - JEP 456
我们经常在代码中定义临时变量或模式变量,这些变量在代码中保持未使用。这往往是由于语言限制,移除它们是被禁止的或会引入副作用。异常、switch 模式和 Lambda 表达式是我们在某个作用域内定义变量或模式,但我们从未真正使用它们的例子:
try {
int number = someNumber / 0;
} catch (ArithmeticException exception) {
System.err.println("除以零");
}
switch (obj) {
case Integer i -> System.out.println("是整数");
case Float f -> System.out.println("是浮点数");
case String s -> System.out.println("是字符串");
default -> System.out.println("默认");
}
try (Connection connection = DriverManager.getConnection(url, user, pwd)) {
LOGGER.info(STR.""
+ "数据库连接成功"
+ "URL = {url}"
+ "usr = {user}"
+ "pwd = {pwd}");
} catch (SQLException e) {}
大约 9 分钟