Java SE 21 新增特性

作者:Grey

原文地址:

博客园:Java SE 21 新增特性

CSDN:Java SE 21 新增特性

源码

源仓库: Github:java_new_features

镜像仓库: GitCode:java_new_features

Record Patterns

该功能首次在 Java SE 19 中预览,在Java SE 20中发布第二次预览版,在此版本中成为永久性功能。这意味着它可以在任何为 Java SE 21 编译的程序中使用,而无需启用预览功能。

示例代码如下

package git.snippets.jdk21;

/**
* record 模式匹配增强
* 无须增加 --enable-preview参数
*
* @author <a href="mailto:410486047@qq.com">Grey</a>
* @date 2023/09/25
* @since 21
*/
public class RecordTest {
public static void main(String[] args) {
Points points = new Points(1, 2);
Line line = new Line(new Points(1, 2), new Points(3, 4));
printPoints(points);
printLine(line);
} private static void printPoints(Object object) {
if (object instanceof Points(int x, int y)) {
System.out.println("jdk 19 object is a position, x = " + x + ", y = " + y);
}
if (object instanceof Points points) {
System.out.println("pre jdk 19 object is a position, x = " + points.x()
+ ", y = " + points.y());
}
switch (object) {
case Points position -> System.out.println("pre jdk 19 object is a position, x = " + position.x()
+ ", y = " + position.y());
default -> throw new IllegalStateException("Unexpected value: " + object);
}
switch (object) {
case Points(int x, int y) -> System.out.println(" jdk 19 object is a position, x = " + x
+ ", y = " + y);
default -> throw new IllegalStateException("Unexpected value: " + object);
} } public static void printLine(Object object) {
if (object instanceof Line(Points(int x1, int y1), Points(int x2, int y2))) {
System.out.println("object is a path, x1 = " + x1 + ", y1 = " + y1
+ ", x2 = " + x2 + ", y2 = " + y2);
}
switch (object) {
case Line(Points(int x1, int y1), Points(int x2, int y2)) ->
System.out.println("object is a path, x1 = " + x1 + ", y1 = " + y1
+ ", x2 = " + x2 + ", y2 = " + y2);
// other cases ...
default -> throw new IllegalStateException("Unexpected value: " + object);
}
} } record Points(int x, int y) {
} record Line(Points from, Points to) {
}

Switch 匹配增强

该功能首次在 Java SE 17 中预览,在在此版本中成为永久性功能。这意味着它可以在任何为 Java SE 21 编译的程序中使用,而无需启用预览功能。

package git.snippets.jdk21;

/**
* switch类型增强匹配
* 无须增加预览参数
*
* @author <a href="mailto:410486047@qq.com">Grey</a>
* @date 2023/09/25
* @since 21
*/
public class SwitchMatchTest {
public static void main(String[] args) {
switchMatch(3);
switchMatch("HELLO");
switchMatch("hello world");
switchMatch(null);
} static void switchMatch(Object obj) {
switch (obj) {
case String s when s.length() > 5 -> System.out.println(s.toUpperCase());
case String s -> System.out.println(s.toLowerCase());
case Integer i -> System.out.println(i * i);
case null -> System.out.println("null obj");
default -> {
}
}
}
}

String template(预览功能)

作为本版本的预览功能推出。字符串模板是对 Java 现有字符串字面量和文本块的补充,它将字面文本与嵌入式表达式和模板处理器结合起来,从而产生专门的结果。

在 Java SE 21之前,字符串的拼接可以用下述三种方式

public static void stringTestBefore21() {
int a = 1;
int b = 2; String concatenated = a + " times " + b + " = " + a * b;
String format = String.format("%d times %d = %d", a, b, a * b);
String formatted = "%d times %d = %d".formatted(a, b, a * b);
System.out.println(concatenated);
System.out.println(format);
System.out.println(formatted);
}

Java SE 21可以用更直观的方法实现字符串的拼接

 public static void stringTest21() {
int a = 1;
int b = 2; String interpolated = STR. "\{ a } times \{ b } = \{ a * b }" ;
System.out.println(interpolated); String dateMessage = STR. "Today's date: \{
LocalDate.now().format(
// We could also use DateTimeFormatter.ISO_DATE
DateTimeFormatter.ofPattern("yyyy-MM-dd")
) }" ;
System.out.println(dateMessage); int httpStatus = 200;
String errorMessage = "error pwd"; String json = STR. """
{
"httpStatus": \{ httpStatus },
"errorMessage": "\{ errorMessage }"
}""" ;
System.out.println(json);
}

Unnamed Patterns and Variables(预览功能)

作为预览功能引入,未命名模式匹配一个记录组件,但不声明组件的名称或类型。未命名变量是可以初始化但不使用的变量,都可以使用下划线字符 (_) 来表示它们。

例如:

   try {
int number = Integer.parseInt(string);
} catch (NumberFormatException e) {
System.err.println("Not a number");
}

其中 e 是未使用的变量,可以写成

   try {
int number = Integer.parseInt(string);
} catch (NumberFormatException _) {
System.err.println("Not a number");
}

再如

        Object object = null;
if (object instanceof Points(int x, int y)) {
System.out.println("object is a position, x = " + x);
}

其中 y 是未使用的变量,可以写成

        Object object = null;
if (object instanceof Points(int x, int _)) {
System.out.println("object is a position, x = " + x);
}

switch 表达式中也可以有类似的用法,例如

        Object obj = null;
switch (obj) {
case Byte b -> System.out.println("Integer number");
case Short s -> System.out.println("Integer number");
case Integer i -> System.out.println("Integer number");
case Long l -> System.out.println("Integer number"); case Float f -> System.out.println("Floating point number");
case Double d -> System.out.println("Floating point number"); default -> System.out.println("Not a number");
}

也可以写成

Object obj = null;
switch (obj) {
case Byte _ -> System.out.println("Integer number");
case Short _ -> System.out.println("Integer number");
case Integer _ -> System.out.println("Integer number");
case Long _ -> System.out.println("Integer number"); case Float _ -> System.out.println("Floating point number");
case Double _ -> System.out.println("Floating point number"); default -> System.out.println("Not a number");
}

Unnamed Classes and Instance Main Methods (预览功能)

预览功能,简言之,就是main方法可以更加精简,原先写一个 Hello World 需要这样做

public class UnnamedClassesAndInstanceMainMethodsTest {
public static void main(String[] args) {
System.out.println("hello world");
}
}

现在可以简化成

public class UnnamedClassesAndInstanceMainMethodsTest {

    void main() {
System.out.println("hello world");
} }

注:上述代码需要在命令行运行,目前IDE还不支持,在命令行下执行:

java --enable-preview --source 21 UnnamedClassesAndInstanceMainMethodsTest.java

输出:hello world

更多

Java SE 7及以后各版本新增特性,持续更新中...

参考资料

Java Language Changes for Java SE 21

JDK 21 Release Notes

JAVA 21 FEATURES(WITH EXAMPLES

Java SE 21 新增特性的更多相关文章

  1. Java SE 8 新增特性

    Java SE 8 新增特性 作者:Grey 原文地址: Java SE 8 新增特性 源码 源仓库: Github:java_new_features 镜像仓库: GitCode:java_new_ ...

  2. Java SE 15 新增特性

    Java SE 15 新增特性 作者:Grey 原文地址:Java SE 15 新增特性 源码 源仓库: Github:java_new_features 镜像仓库: GitCode:java_new ...

  3. Java SE 16 新增特性

    Java SE 16 新增特性 作者:Grey 原文地址:Java SE 16 新增特性 源码 源仓库: Github:java_new_features 镜像仓库: GitCode:java_new ...

  4. Java SE 17 新增特性

    Java SE 17 新增特性 作者:Grey 原文地址:Java SE 17 新增特性 源码 源仓库: Github:java_new_features 镜像仓库: GitCode:java_new ...

  5. Java SE 9 新增特性

    Java SE 9 新增特性 作者:Grey 原文地址: Java SE 9 新增特性 源码 源仓库: Github:java_new_features 镜像仓库: GitCode:java_new_ ...

  6. Java SE 10 新增特性

    Java SE 10 新增特性 作者:Grey 原文地址:Java SE 10 新增特性 源码 源仓库: Github:java_new_features 镜像仓库: GitCode:java_new ...

  7. Java SE 11 新增特性

    Java SE 11 新增特性 作者:Grey 原文地址:Java SE 11 新增特性 源码 源仓库: Github:java_new_features 镜像仓库: GitCode:java_new ...

  8. Java SE 12 新增特性

    Java SE 12 新增特性 作者:Grey 原文地址:Java SE 12 新增特性 源码 源仓库: Github:java_new_features 镜像仓库: GitCode:java_new ...

  9. Java SE 13 新增特性

    Java SE 13 新增特性 作者:Grey 原文地址:Java SE 13 新增特性 源码 源仓库: Github:java_new_features 镜像仓库: GitCode:java_new ...

  10. Java SE 14 新增特性

    Java SE 14 新增特性 作者:Grey 原文地址:Java SE 14 新增特性 源码 源仓库: Github:java_new_features 镜像仓库: GitCode:java_new ...

随机推荐

  1. Python异步编程之web框架 异步vs同步 数据库IO任务压测对比

    测试基本信息 主题:比较异步框架和同步框架在数据库IO操作的性能差异 python版本:python 3.8 数据库:mysql 8.0.27 (docker部署) 压测工具:locust web框架 ...

  2. JuiceFS 社区版 v1.1- Beta 发布,新增五个实用功能

    我们很高兴地宣布 JuiceFS v1.1-Beta 版本正式发布啦!这是一个功能丰富的版本,带来了许多实用的新功能和改进.在这个版本中我们新增了以下功能: 目录配额:为目录设置配额限制,控制其大小和 ...

  3. How to build a OR condition in Elasticsearch Query DSL

    How to build a OR condition in Elasticsearch Query DSL 参考 Query Example Query DSL 表达方

  4. PostgreSQL 12 文档: PostgreSQL 服务端程序

    PostgreSQL 服务器应用   这一部分包含PostgreSQL服务器应用和支持工具的参考信息.这些命令只在数据库服务器所在的主机上运行才有用.其他工具程序在PostgreSQL 客户端应用中列 ...

  5. PostgreSQL 12 文档: 部分 II. SQL 语言

    部分 II. SQL 语言 这部份描述在PostgreSQL中SQL语言的使用.我们从描述SQL的一般语法开始,然后解释如何创建保存数据的结构.如何填充数据库以及如何查询它.中间的部分列出了在SQL命 ...

  6. GC 分代回收算法

    GC 分代回收算法 1.首先了解JVM堆内存是如何分配的. 年轻代内部  生成区 和 S0 S1 的比例 默认情况下是 8:1 :1 堆内存和永久代存储的内容有区别:  堆内存主要存储的是 : 对象, ...

  7. 记一次线上bug:crontab 被意外清空

    记一次线上bug:crontab 被意外清空 目录 记一次线上bug:crontab 被意外清空 问题概述 问题排查 问题复现 其他测试 总结 又是一次难忘的经历. 问题概述 同事反馈,某台服务器的c ...

  8. 从零配置Webpack项目

    webpack.config.js基本配置 webpack.config.js是webpack的配置文件,在此文件中对项目入口,项目的输出,loader,插件以及环境等进行简单的配置 首先来对webp ...

  9. C语言基础--数组详细说明

    目录 一.什么是数组 二.一维数组 1.一维数组创建 2.一维数组的使用 2.1 索引值 2.2 遍历数组 2.3 如何使用sizeof()计算出数组的长度 三.二维数组 1.二维数组的创建 2.二维 ...

  10. 1.简述Hibernate的工作原理。

    (1).首先,Configuration读取Hibernate的配置文件和映射文件中的信息,即加载配置文件和映射文件,并通过Hibernate配置文件生成一个多线程的SessionFactory对象: ...