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