Java 15 instanceof的模式匹配
Java 14引入了instanceof运算符作为预览特性,以具有类型测试模式。类型测试模式具有一个谓词来指定一个带有单个绑定变量的类型。在Java 15中,它仍然是一个预览特性。
语法
if (person instanceof Employee e) {
return e.getEmployeeId();
}
示例
考虑以下示例 –
ApiTester.java
public class APITester {
public static void main(String[] args) {
Person manager = new Manager(23, "Robert");
manager.name = "Robert";
System.out.println(getId(manager));
}
public static int getId(Person person) {
if (person instanceof Employee e) {
return e.getEmployeeId();
}
else if (person instanceof Manager m) {
return m.getManagerId();
}
return -1;
}
}
abstract sealed class Person permits Employee, Manager {
String name;
String getName() {
return name;
}
}
final class Employee extends Person {
String name;
int id;
Employee(int id, String name){
this.id = id;
this.name = name;
}
int getEmployeeId() {
return id;
}
}
non-sealed class Manager extends Person {
int id;
Manager(int id, String name){
this.id = id;
this.name = name;
}
int getManagerId() {
return id;
}
}
编译和运行程序
$javac -Xlint:preview --enable-preview -source 14 APITester.java
$java --enable-preview APITester
输出
23