cover_image

Java19的新特性

码匠乱炖 码匠的流水账
2022年09月21日 15:22
前言
Java19的新特性

Java语言特性系列

  • Java5的新特性

  • Java6的新特性

  • Java7的新特性

  • Java8的新特性

  • Java9的新特性

  • Java10的新特性

  • Java11的新特性

  • Java12的新特性

  • Java13的新特性

  • Java14的新特性

  • Java15的新特性

  • Java16的新特性

  • Java17的新特性

  • Java18的新特性

  • Java19的新特性

  • Java20的新特性

本文主要讲述一下Java19的新特性

版本号

  1. java -version

  2. openjdk version "19" 2022-09-20

  3. OpenJDK Runtime Environment (build 19+36-2238)

  4. OpenJDK 64-Bit Server VM (build 19+36-2238, mixed mode, sharing)

从version信息可以看出是build 19+36

特性列表

JEP 405: Record Patterns (Preview)

instanceof的模式匹配在JDK14作为preview,在JDK15作为第二轮的preview,在JDK16JEP 394: Pattern Matching for instanceof转正 switch模式匹配在JDK17的JEP 406: Pattern Matching for switch (Preview)引入作为preview版本,在JDK18的JEP 420: Pattern Matching for switch (Second Preview)作为第二轮的preview

针对record类型,引入instance of可以这么写

  1. record Point(int x, int y) {}


  2. static void printSum(Object o) {

  3. if (o instanceof Point p) {

  4. int x = p.x();

  5. int y = p.y();

  6. System.out.println(x+y);

  7. }

  8. }

现在可以这么写

  1. record Point(int x, int y) {}


  2. void printSum(Object o) {

  3. if (o instanceof Point(int x, int y)) {

  4. System.out.println(x+y);

  5. }

  6. }

比较复杂的例子:

  1. record Point(int x, int y) {}

  2. enum Color { RED, GREEN, BLUE }

  3. record ColoredPoint(Point p, Color c) {}

  4. record Rectangle(ColoredPoint upperLeft, ColoredPoint lowerRight) {}


  5. Rectangle r = new Rectangle(new ColoredPoint(new Point(x1, y1), c1),

  6. new ColoredPoint(new Point(x2, y2), c2));


  7. static void printXCoordOfUpperLeftPointWithPatterns(Rectangle r) {

  8. if (r instanceof Rectangle(ColoredPoint(Point(var x, var y), var c),

  9. var lr)) {

  10. System.out.println("Upper-left corner: " + x);

  11. }

  12. }

如果是泛型record的话:

  1. record Box<T>(T t) {}


  2. static void test1(Box<Object> bo) {

  3. if (bo instanceof Box<Object>(String s)) {

  4. System.out.println("String " + s);

  5. }

  6. }

  7. static void test2(Box<Object> bo) {

  8. if (bo instanceof Box<String>(var s)) {

  9. System.out.println("String " + s);

  10. }

  11. }

兑换合集后可阅读剩余76%
#Java新特性
已完结 共13个
合集详情
  • 1. Java9的新特性
  • 2. Java10的新特性
  • 3. Java11的新特性
兑换合集后可阅读剩余76%

#Java新特性

微信扫一扫付费阅读本文
继续滑动看下一个
码匠的流水账
向上滑动看下一个