Java从8到21的语言新特性

try-with-resource可以使用既有的变量

// java 9 之前
try (InputStream is = Files.newInputStream(Paths.get("1111"))) {
    // do something
}

// java 9 之后可以这样了
InputStream is = Files.newInputStream(Paths.get("1111"));
try (is) {
    // do something
}

钻石操作符扩展

现在钻石操作符可以和匿名类一起使用:

FooClass<Integer> fc = new FooClass<>(1) {
};

FooClass<? extends Integer> fc0 = new FooClass<>(1) {

};

FooClass<?> fc1 = new FooClass<>(1) {
};

接口私有方法

接口可以包含私有方法,主要用于防止默认方法过长:

interface InterfaceWithPrivateMethods {

    private static String staticPrivate() {
        return "static private";
    }

    private String instancePrivate() {
        return "instance private";
    }

    default void check() {
        String result = staticPrivate();
        InterfaceWithPrivateMethods pvt = new InterfaceWithPrivateMethods() {

        };
        result = pvt.instancePrivate();
    }
}

类型推断var

类型推断仅可用于局部变量和lambda表达式中:

var x = 1;

switch表达式

在此之前:

// 之前
boolean isTodayHoliday;
switch (day) {
    case "MONDAY":
    case "TUESDAY":
    case "WEDNESDAY":
    case "THURSDAY":
    case "FRIDAY":
        isTodayHoliday = false;
        break;
    case "SATURDAY":
    case "SUNDAY":
        isTodayHoliday = true;
        break;
    default:
        throw new IllegalArgumentException("What's a " + day);
}

// 从14开始
boolean isTodayHoliday = switch (day) {
    case "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY" -> false;
    case "SATURDAY", "SUNDAY" -> true;
    default -> throw new IllegalArgumentException("What's a " + day);
};

// 从17开始
static record Human (String name, int age, String profession) {}

public String checkObject(Object obj) {
    return switch (obj) {
        case Human h -> "Name: %s, age: %s and profession: %s".formatted(h.name(), h.age(), h.profession());
        case Circle c -> "This is a circle";
        case Shape s -> "It is just a shape";
        case null -> "It is null";
        default -> "It is an object";
    };
}

public String checkShape(Shape shape) {
    return switch (shape) {
        case Triangle t && (t.getNumberOfSides() != 3) -> "This is a weird triangle";
        case Circle c && (c.getNumberOfSides() != 0) -> "This is a weird circle";
        default -> "Just a normal shape";
    };
}

字符块

String multiline = """
    A quick brown fox jumps over a lazy dog; \
    the lazy dog howls loudly.""";

字符串模板

String interpolationUsingSTRProcessor(String feelsLike, String temperature, String unit) {
    return STR
      . "Today's weather is \{ feelsLike }, with a temperature of \{ temperature } degrees \{ unit }" ;
}

// 或者字串块
String interpolationOfJSONBlock(String feelsLike, String temperature, String unit) {
    return STR
      . """
      {
        "feelsLike": "\{ feelsLike }",
        "temperature": "\{ temperature }",
        "unit": "\{ unit }"
      }
      """ ;
}

也可以带格式化的:

String interpolationOfJSONBlockWithFMT(String feelsLike, float temperature, String unit) {
    return FMT
      . """
      {
        "feelsLike": "%1s\{ feelsLike }",
        "temperature": "%2.2f\{ temperature }",
        "unit": "%1s\{ unit }"
      }
      """ ;
}

参见baeldung的说明。

模式匹配 instanceof

可以在instanceof判断的同时声明新的变量了:

if (obj instanceof String str) {
    int len = str.length();

}

Records

public record User(int id, String password) { };

Sealed Classes (JEP 360)

只允许特定的类继承,配合模式匹配会很好用,即可以确定匹配到所有已知的类型:

public abstract sealed class Person permits Employee, Manager {
}

public final class Employee extends Person {
}

public non-sealed class Manager extends Person {
}

参考:

  1. New Features in Java 14
  2. New Features in Java 17
posted @ 2024-03-16 12:19  Narcissu5  阅读(51)  评论(0编辑  收藏  举报