经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
Java SE 21 新增特性
来源:cnblogs  作者:Grey Zeng  时间:2023/9/25 16:49:36  对本文有异议

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 编译的程序中使用,而无需启用预览功能。

示例代码如下

  1. package git.snippets.jdk21;
  2. /**
  3. * record 模式匹配增强
  4. * 无须增加 --enable-preview参数
  5. *
  6. * @author <a href="mailto:410486047@qq.com">Grey</a>
  7. * @date 2023/09/25
  8. * @since 21
  9. */
  10. public class RecordTest {
  11. public static void main(String[] args) {
  12. Points points = new Points(1, 2);
  13. Line line = new Line(new Points(1, 2), new Points(3, 4));
  14. printPoints(points);
  15. printLine(line);
  16. }
  17. private static void printPoints(Object object) {
  18. if (object instanceof Points(int x, int y)) {
  19. System.out.println("jdk 19 object is a position, x = " + x + ", y = " + y);
  20. }
  21. if (object instanceof Points points) {
  22. System.out.println("pre jdk 19 object is a position, x = " + points.x()
  23. + ", y = " + points.y());
  24. }
  25. switch (object) {
  26. case Points position -> System.out.println("pre jdk 19 object is a position, x = " + position.x()
  27. + ", y = " + position.y());
  28. default -> throw new IllegalStateException("Unexpected value: " + object);
  29. }
  30. switch (object) {
  31. case Points(int x, int y) -> System.out.println(" jdk 19 object is a position, x = " + x
  32. + ", y = " + y);
  33. default -> throw new IllegalStateException("Unexpected value: " + object);
  34. }
  35. }
  36. public static void printLine(Object object) {
  37. if (object instanceof Line(Points(int x1, int y1), Points(int x2, int y2))) {
  38. System.out.println("object is a path, x1 = " + x1 + ", y1 = " + y1
  39. + ", x2 = " + x2 + ", y2 = " + y2);
  40. }
  41. switch (object) {
  42. case Line(Points(int x1, int y1), Points(int x2, int y2)) ->
  43. System.out.println("object is a path, x1 = " + x1 + ", y1 = " + y1
  44. + ", x2 = " + x2 + ", y2 = " + y2);
  45. // other cases ...
  46. default -> throw new IllegalStateException("Unexpected value: " + object);
  47. }
  48. }
  49. }
  50. record Points(int x, int y) {
  51. }
  52. record Line(Points from, Points to) {
  53. }

Switch 匹配增强

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

  1. package git.snippets.jdk21;
  2. /**
  3. * switch类型增强匹配
  4. * 无须增加预览参数
  5. *
  6. * @author <a href="mailto:410486047@qq.com">Grey</a>
  7. * @date 2023/09/25
  8. * @since 21
  9. */
  10. public class SwitchMatchTest {
  11. public static void main(String[] args) {
  12. switchMatch(3);
  13. switchMatch("HELLO");
  14. switchMatch("hello world");
  15. switchMatch(null);
  16. }
  17. static void switchMatch(Object obj) {
  18. switch (obj) {
  19. case String s when s.length() > 5 -> System.out.println(s.toUpperCase());
  20. case String s -> System.out.println(s.toLowerCase());
  21. case Integer i -> System.out.println(i * i);
  22. case null -> System.out.println("null obj");
  23. default -> {
  24. }
  25. }
  26. }
  27. }

String template(预览功能)

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

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

  1. public static void stringTestBefore21() {
  2. int a = 1;
  3. int b = 2;
  4. String concatenated = a + " times " + b + " = " + a * b;
  5. String format = String.format("%d times %d = %d", a, b, a * b);
  6. String formatted = "%d times %d = %d".formatted(a, b, a * b);
  7. System.out.println(concatenated);
  8. System.out.println(format);
  9. System.out.println(formatted);
  10. }

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

  1. public static void stringTest21() {
  2. int a = 1;
  3. int b = 2;
  4. String interpolated = STR. "\{ a } times \{ b } = \{ a * b }" ;
  5. System.out.println(interpolated);
  6. String dateMessage = STR. "Today's date: \{
  7. LocalDate.now().format(
  8. // We could also use DateTimeFormatter.ISO_DATE
  9. DateTimeFormatter.ofPattern("yyyy-MM-dd")
  10. ) }" ;
  11. System.out.println(dateMessage);
  12. int httpStatus = 200;
  13. String errorMessage = "error pwd";
  14. String json = STR. """
  15. {
  16. "httpStatus": \{ httpStatus },
  17. "errorMessage": "\{ errorMessage }"
  18. }""" ;
  19. System.out.println(json);
  20. }

Unnamed Patterns and Variables(预览功能)

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

例如:

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

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

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

再如

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

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

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

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

  1. Object obj = null;
  2. switch (obj) {
  3. case Byte b -> System.out.println("Integer number");
  4. case Short s -> System.out.println("Integer number");
  5. case Integer i -> System.out.println("Integer number");
  6. case Long l -> System.out.println("Integer number");
  7. case Float f -> System.out.println("Floating point number");
  8. case Double d -> System.out.println("Floating point number");
  9. default -> System.out.println("Not a number");
  10. }

也可以写成

  1. Object obj = null;
  2. switch (obj) {
  3. case Byte _ -> System.out.println("Integer number");
  4. case Short _ -> System.out.println("Integer number");
  5. case Integer _ -> System.out.println("Integer number");
  6. case Long _ -> System.out.println("Integer number");
  7. case Float _ -> System.out.println("Floating point number");
  8. case Double _ -> System.out.println("Floating point number");
  9. default -> System.out.println("Not a number");
  10. }

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

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

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

现在可以简化成

  1. public class UnnamedClassesAndInstanceMainMethodsTest {
  2. void main() {
  3. System.out.println("hello world");
  4. }
  5. }

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

  1. 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

原文链接:https://www.cnblogs.com/greyzeng/p/17727833.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号