instanceof 增强
在 Java 16 中,instanceof
操作符得到了增强,称为 模式匹配(Pattern Matching for instanceof)。这一新特性简化了 instanceof
检查和类型转换的代码,减少了冗余代码,提高了可读性和开发效率。
在 Java 16 之前,如果要使用 instanceof
检查一个对象的类型,并对其进行强制类型转换(cast),通常需要写两次变量的类型:
public class OldInstanceOfListExample {
public static void main(String[] args) {
List<Object> items = List.of("Hello", 123, 3.14);
for (Object item : items) {
if (item instanceof String) {
String str = (String) item; // 必须显式强制转换为 String
System.out.println("String: " + str.toUpperCase());
} else if (item instanceof Integer) {
Integer num = (Integer) item; // 必须显式强制转换为 Integer
System.out.println("Integer: " + (num + 10));
} else if (item instanceof Double) {
Double dbl = (Double) item; // 必须显式强制转换为 Double
System.out.println("Double: " + (dbl * 2));
}
}
}
}
Java 16 引入了 模式匹配(Pattern Matching),使得 instanceof
不仅可以检查类型,还能同时完成类型转换,并将转换后的结果绑定到一个变量:
import java.util.List;
public class InstanceOfListExample {
public static void main(String[] args) {
List<Object> items = List.of("Hello", 123, 3.14);
for (Object item : items) {
if (item instanceof String str) {
System.out.println("String: " + str.toUpperCase());
} else if (item instanceof Integer num) {
System.out.println("Integer: " + (num + 10));
} else if (item instanceof Double dbl) {
System.out.println("Double: " + (dbl * 2));
}
}
}
}