JDK new features

来自WHY42

JDK 22

JDK 21

Pattern Matching for switch

Previously, switch was very limited: the cases could only test exact equality, and only for values of a few types: numbers, Enum types and Strings.

This feature enhances switch to work on any type and to match on more complex patterns.

These additions are backwards compatible, switch with the traditional constants work just as before, for example, with Enum values:

enum Status { Normal, Deleted }
public int getStatus(Status s) {
    return switch(s) {
        case Normal -> 0;
        case Deleted -> -1;
    };
}

However, now it also works with type patterns introduced by JEP 394: Pattern Matching for instanceof:

class Item {}
class Text extends Item {}
class Image extends Item {
    public String getImageType() { return "png"; }
}

public void printItem(Item item) {
    var msg = switch(item) {
        case Text -> "Text";
        case Image -> "Image";
        default -> "Unknow item";
    };
    System.out.println(msg);
}

A pattern supports guards, written as type pattern when guard expression:

var msg = switch(item) {
    case Text -> "Text";
    case Image img when img.size > 1024 -> "Large Image";
    case Image -> "Image";
    default -> "Unknow item";
};

Similarly to the type patterns in if conditions, the scope of the pattern variables are flow sensitive. Generally it works just as you'd expect, but there are many rules and edge cases involved.

JDK 17

JEP 409: Sealed Classes

Sealed Classes have been added to the Java Language. Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them.

Sealed Classes were proposed by JEP 360 and delivered in JDK 15 as a preview feature. They were proposed again, with refinements, by JEP 397 and delivered in JDK 16 as a preview feature. Now in JDK 17, Sealed Classes are being finalized with no changes from JDK 16.

For further details, see JEP 409.[1]

JDK 11