Java 17新特性讲解与代码实例

Java 17是Java SE 17的开源参考实现,于2021年9月14日正式发布,是Java 11以来的又一个长期支持(LTS)版本。Java 17中有一些新的特性和改进,本文将对它们进行简要的介绍和示例。

密封类

密封类和接口限制了哪些其他类或接口可以扩展或实现它们,增强了封装性和可维护性。密封类由JEP 360并在JDK 15中作为预览功能交付。它们再次被提出,并进行了改进,由JEP 397并在JDK 16中作为预览功能提供。现在,在JDK 17中,密封类正在最终确定,与JDK 16没有任何更改。

要定义一个密封类或接口,需要使用sealed修饰符,并且在声明中指定允许扩展或实现它的其他类或接口。这些类或接口被称为子类或子接口。子类或子接口可以使用final修饰符来表示它们不能被进一步扩展或实现,或者使用sealed修饰符来表示它们也是密封的,并且需要指定它们的子类或子接口,或者使用non-sealed修饰符来表示它们不是密封的,并且可以被任意的类或接口扩展或实现。

例如,我们可以定义一个密封的形状接口Shape,并且指定它只能被Circle、Rectangle和Triangle这三个类实现:

public sealed interface Shape permits Circle, Rectangle, Triangle {
    double area();
}

然后,我们可以定义这三个类,并且分别使用finalsealednon-sealed修饰符:

public final class Circle implements Shape {
    private final double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double area() {
        return Math.PI * radius * radius;
    }
}

public sealed class Rectangle implements Shape permits Square {
    private final double length;
    private final double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    public double area() {
        return length * width;
    }
}

public non-sealed class Triangle implements Shape {
    private final double base;
    private final double height;

    public Triangle(double base, double height) {
        this.base = base;
        this.height = height;
    }

    public double area() {
        return base * height / 2;
    }
}

注意,Square是Rectangle的子类,并且也是密封的:

public final class Square extends Rectangle {
    public Square(double side) {
        super(side, side);
    }
}

这样,我们就可以保证Shape接口只能被这四个类实现,而不会有其他的可能性。我们也可以使用模式匹配来对不同的形状进行操作,例如:

public static void printArea(Shape shape) {
    if (shape instanceof Circle c) {
        System.out.println("The area of the circle is " + c.area());
    } else if (shape instanceof Rectangle r) {
        System.out.println("The area of the rectangle is " + r.area());
    } else if (shape instanceof Triangle t) {
        System.out.println("The area of the triangle is " + t.area());
    }
}

switch表达式

switch表达式允许switch有返回值,并且可以直接作为结果赋值给一个变量,简化了多分支的逻辑。switch表达式由JEP 325并在JDK 12中作为预览功能交付。它们再次被提出,并进行了改进,由JEP 354并在JDK 13中作为预览功能提供。它们再次被提出,并进行了改进,由JEP 361并在JDK 14中作为预览功能提供。现在,在JDK 17中,switch表达式正在最终确定,与JDK 14没有任何更改。

要定义一个switch表达式,需要使用->符号来表示每个分支的结果,并且在表达式的末尾加上一个分号。例如,我们可以定义一个根据月份返回季节的switch表达式:

public static String getSeason(int month) {
    return switch (month) {
        case 12, 1, 2 -> "Winter";
        case 3, 4, 5 -> "Spring";
        case 6, 7, 8 -> "Summer";
        case 9, 10, 11 -> "Autumn";
        default -> "Unknown";
    };
}

注意,我们可以使用逗号来分隔多个匹配值,也可以使用default来表示其他情况。我们也可以使用yield关键字来返回一个值,这在需要在返回之前进行一些操作的情况下很有用,例如:

public static String getSeason(int month) {
    return switch (month) {
        case 12, 1, 2 -> {
            System.out.println("It's cold!");
            yield "Winter";
        }
        case 3, 4, 5 -> {
            System.out.println("It's warm!");
            yield "Spring";
        }
        case 6, 7, 8 -> {
            System.out.println("It's hot!");
            yield "Summer";
        }
        case 9, 10, 11 -> {
            System.out.println("It's cool!");
            yield "Autumn";
        }
        default -> {
            System.out.println("It's unknown!");
            yield "Unknown";
        }
    };
}

文本块

文本块允许使用三个双引号来定义一个多行的字符串,避免了转义和拼接的麻烦。文本块由JEP

355并在JDK 13中作为预览功能交付。它们再次被提出,并进行了改进,由JEP 368并在JDK 14中作为预览功能提供。它们再次被提出,并进行了改进,由JEP 378并在JDK 15中作为预览功能提供。现在,在JDK 17中,文本块正在最终确定,与JDK 15没有任何更改。

要定义一个文本块,需要使用三个双引号"""来开始和结束,并且结束的三个双引号不能和开始的在同一行。例如,我们可以定义一个包含JSON数据的文本块:

public static String getJson() {
    return """
    {
        "name": "Java",
        "version": 17,
        "features": [
            "sealed classes",
            "switch expressions",
            "text blocks"
        ]
    }
    """;
}

注意,文本块中的换行符会被保留,而不需要使用\n来表示。我们也可以使用\来表示忽略换行符,或者使用\s来表示一个空格。例如:

public static String getGreeting() {
    return """
    Hello,\
    World!
    """;
}

public static String getPoem() {
    return """
    Twinkle, twinkle, little star,\s
    How I wonder what you are.\s
    Up above the world so high,\s
    Like a diamond in the sky.
    """;
}

模式匹配

模式匹配允许在instanceof和switch中使用模式来测试表达式的类型和结构,提高了代码的可读性和灵活性。模式匹配由JEP 305并在JDK 14中作为预览功能交付。它们再次被提出,并进行了改进,由JEP 375并在JDK 15中作为预览功能提供。它们再次被提出,并进行了改进,由JEP 394并在JDK 16中作为预览功能提供。现在,在JDK 17中,模式匹配正在最终确定,与JDK 16没有任何更改。

要使用模式匹配,需要使用instanceofswitch关键字,并且在测试的类型后面加上一个变量名,用于绑定匹配的值。例如,我们可以使用模式匹配来判断一个对象是否是字符串,并且获取它的长度:

public static void printLength(Object obj) {
    if (obj instanceof String s) {
        System.out.println("The length of the string is " + s.length());
    } else {
        System.out.println("The object is not a string");
    }
}

注意,我们不需要再进行强制类型转换,因为变量s已经被绑定为字符串类型。我们也可以使用模式匹配来判断一个对象是否是密封类的子类,并且获取它的属性:

public static void printShape(Shape shape) {
    switch (shape) {
        case Circle c -> System.out.println("The radius of the circle is " + c.radius());
        case Rectangle r -> System.out.println("The area of the rectangle is " + r.area());
        case Triangle t -> System.out.println("The base of the triangle is " + t.base());
        default -> System.out.println("Unknown shape");
    }
}

注意,我们不需要再进行类型检查或者类型转换,因为变量crt已经被绑定为相应的类型。

增强型伪随机数生成器

增强型伪随机数生成器为PRNG提供了新的接口类型和实现,包括可跳转的PRNG和一类额外的可拆分PRNG算法(LXM)。增强型伪随机数生成器由JEP 356并在JDK 17中作为正式功能提供。

要使用增强型伪随机数生成器,需要使用java.util.random包中的新的接口和类。例如,我们可以使用RandomGenerator接口来获取一个PRNG的实例,并且使用它来生成各种类型的随机数:

public static void generateRandomNumbers() {
    RandomGenerator random = RandomGenerator.getDefault();
    System.out.println("A random boolean: " + random.nextBoolean());
    System.out.println("A random int: " + random.nextInt());
    System.out.println("A random long: " + random.nextLong());
    System.out.println("A random float: " + random.nextFloat());
    System.out.println("A random double: " + random.nextDouble());
}

注意,RandomGenerator接口提供了很多方便的方法来生成不同范围和分布的随机数,例如nextInt(int bound)nextLong(long bound)nextGaussian()等。我们也可以使用RandomGeneratorFactory类来获取不同的PRNG算法的实例,例如:

public static void useDifferentAlgorithms() {
    RandomGenerator random1 = RandomGeneratorFactory.of("L32X64MixRandom");
    RandomGenerator random2 = RandomGeneratorFactory.of("L64X128MixRandom");
    RandomGenerator random3 = RandomGeneratorFactory.of("L128X256MixRandom");
    System.out.println("Using L32X64MixRandom: " + random1.nextInt());
    System.out.println("Using L64X128MixRandom: " + random2.nextInt());
    System.out.println("Using L128X256MixRandom: " + random3.nextInt());
}

注意,RandomGeneratorFactory类提供了很多方法来获取或者查询不同的PRNG算法,例如of(String name)all()preferred()等。我们也可以使用JumpableRandomGenerator接口或者SplittableRandomGenerator接口来获取一个可跳转或者可拆分的PRNG实例,并且使用它们来生成不同的子生成器,例如:

public static void useJumpableOrSplittableGenerators() {
    JumpableRandomGenerator jumpable = RandomGeneratorFactory.jumpable();
    SplittableRandomGenerator splittable = RandomGeneratorFactory.splittable();
    System.out.println("Using the original jumpable generator: " + jumpable.nextInt());
    System.out.println("Using the original splittable generator: " + splittable.nextInt());
    JumpableRandomGenerator jumped = jumpable.jump();
    SplittableRandomGenerator splitted = splittable.split();
    System.out.println("Using the jumped generator: " + jumped.nextInt());
    System.out.println("Using the splitted generator: " + splitted.nextInt());
}

注意,JumpableRandomGenerator接口和SplittableRandomGenerator接口都继承自RandomGenerator接口,并且提供了额外的方法来生成子生成器,例如jump()split()等。这些子生成器可以用于并行计算或者其他场景。

新的macOS渲染管道

新的macOS渲染管道使用Apple Metal加速渲染API来替代被Apple弃用的OpenGL API。新的macOS渲染管道由JEP 382并在JDK 17中作为正式功能提供。

要使用新的macOS渲染管道,需要在运行Java程序时设置系统属性:

-Dsun.java2d.metal=true

这样,Java 2D API和Swing API用于渲染的Java 2D API就可以使用Metal API来加速渲染。这对于Java程序是透明的,因为这是内部实现的区别,对Java API没有影响。Metal管道需要macOS 10.14.x或更高版本。在早期版本上设置它的尝试将被忽略。

猜你喜欢

转载自blog.csdn.net/caicai250/article/details/131415249