@) 참고 - What’s New in Java 15
Java 15에 추가된 기능들 에대해 알아보자
Records
(JEP 384)
The record is a new type of class in Java that makes it easy to create immutable data objects.
불변 DTO 생성
public class Person { private final String name; private final int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } }
public record Person(String name, int age) { }
Sealed
Classes (JEP 360)
→ two new keywords -
sealed
and permits
public abstract sealed class Person permits Employee, Manager { //... }
Person 클래스는 Employee 와 Manager 클래스에서만 상송가능함
public final class Employee extends Person { } public non-sealed class Manager extends Person { }
Sealed class 를 상속한 클래스는 무조건 final, sealed 혹은 non-sealed로 선언되어야함
if (person instanceof Employee) { return ((Employee) person).getEmployeeId(); } else if (person instanceof Manager) { return ((Manager) person).getSupervisorId(); }
이런 if else 구문에서 sealed 클래스를 사용하면 컴파일 단계에서 모든 자식 클래스가 다루어 졌는 지에대한 확인이 가능함
- Pattern Matching Type Checks (JEP 375)
이 기능의 목적은 타입 체킹시 발생하는 boilerplate code 를 없애는 것임
if (person instanceof Employee) { Employee employee = (Employee) person; Date hireDate = employee.getHireDate(); //... }
if (person instanceof Employee employee) { Date hireDate = employee.getHireDate(); //... }
instanceof
수행시 바로 변수의 선언 및 타입변환 까지 수행할 수 있다.