java 21 - switch 模式匹配
在java 17 对switch 语句做了增强后, 21提出了模式匹配。之前switch的选择器表达式的类型必须是整型原始类型(char、byte、short 或 int)、相应的封装类型(Character、Byte、Short 或 Integer)、String 或枚举类型。java 21对此进行了扩展,并要求选择器表达式的类型是整型原始类型或任何引用类型。
enum Fruit {APPLE, BANANA, ORANGE, LEMON}
static class A {}
static class B {}
static class C {}
private static void test(Object o) {
switch (o) {
case null -> System.out.println("nll !!!");
case String s -> System.out.println(s);
case Integer i -> System.out.println(i);
case A a -> System.out.println(a.getClass());
case B b -> System.out.println(b.getClass());
case C c -> System.out.println(c.getClass());
case Fruit.APPLE -> System.out.println("苹果");
default -> System.out.println("default");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
上次更新: 2024/01/11 17:06:16