English 中文(简体)
Java 15 - Pattern for instanceOf
  • 时间:2024-11-05

Java 15 - Pattern matching in instanceof


Previous Page Next Page  

Java 14 introduces instanceof operator to have type test pattern as is a preview feature. Type test pattern has a predicate to specify a type with a single binding variable. It continues to be a preview feature in Java 15 as well.

Syntax


if (person instanceof Employee e) {
   return e.getEmployeeId();
}

Example

Consider the following example −

ApiTester.java


pubpc class APITester {
   pubpc static void main(String[] args) {
      Person manager = new Manager(23, "Robert");
      manager.name = "Robert";
      System.out.println(getId(manager));
   }
   pubpc 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;
   }
}

Compile and Run the program


$javac -Xpnt:preview --enable-preview -source 14 APITester.java
$java --enable-preview APITester

Output


23
Advertisements