본문 바로가기

프로그래밍언어/JAVA

[Java] Record

반응형

1. Record ?

Record 는 JDK 14 에서 preview feature 로 처음 추가된 기능으로 불변 데이터 전달을 위한 클래스 타입이다. Record 는 생성자와 getter, equals(), hashCode(), toString() 과 같이 일반적인 데이터 클래스가 가지게 되는 기능을 자동으로 가지게 되어 boilerplate 코드들을 제거해준다.

 

Record 의 선언부의 헤더를 통해서 필드가 선언된다. 이때 Record 의 필드는 모두 불변이기 떄문에 내부적으로 final 로 선언된다.

 

record Rectangle(double length, double width) { }

public final class Rectangle {
    private final double length;
    private final double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    double length() { return this.length; }
    double width()  { return this.width; }

    // Implementation of equals() and hashCode(), which specify
    // that two record objects are equal if they
    // are of the same type and contain equal field values.
    public boolean equals...
    public int hashCode...

    // An implementation of toString() that returns a string
    // representation of all the record class's fields,
    // including their names.
    public String toString() {...}
}

 

위의 예제는 record 로 선언된 클래스와 일반 클래스를 비교한 것이다. 위의 record 로 선언된 Rectangle 클래스는 아래의 일반 class 로 선언된 Rectangle 과 같은 구성을 가지게 된다.

 

Record 클래스는 클래스의 이름, 각 필드의 이름과 타입을 선언하는 헤더, 그리고 바디로 구성된다.

헤더에 선언된 이름과 타입에 따라서 record 클래스의 필드들이 생성되는데, 이때 private final 로 불변값으로 정의된다. 또한 동명의 public 접근메서드가 함께 생성된다. (getter 라고 생각하면 된다.) 생성자 또한 헤더에 선언된 값과 동일한 형태로 생성된다. equals() 와 hashcode() 는 각 record 인스턴스가 같은 타입, 같은 필드 값을 가지고 있는 지 등을 비교하도록 구현된다.

 

이렇게 선언된 record 클래스는 아래와 같이 new 키워드를 사용하여 인스턴스를 생성하여 사용할 수 있다.

 

Rectangle r = new Rectangle(4,5);

2. Record 클래스 구현

 

Record 클래스에 자동으로 생성되는 생성자 말고 개발자가 직접 생성자를 구현할 수도 있다.

아래의 예제는 Rectangle 클래스의 생성자를 직접 구현하여 내부에서 매개변수의 예외처리를 하고있다.

 

record Rectangle(double length, double width) {
    public Rectangle(double length, double width) {
        if (length <= 0 || width <= 0) {
            throw new java.lang.IllegalArgumentException(
                String.format("Invalid dimensions: %f, %f", length, width));
        }
        this.length = length;
        this.width = width;
    }
}

 

record 클래스의 생성자는 선언부의 헤더에 선언된 값들을 생략한 compact contstructor 를 구현할 수 있다. 아래 예제에서는 record Rectangle double length, double width 를 입력받는 부분을 생략하고 compact constructor 로 구현하였다.

 

record Rectangle(double length, double width) {
    public Rectangle {
        if (length <= 0 || width <= 0) {
            throw new java.lang.IllegalArgumentException(
                String.format("Invalid dimensions: %f, %f", length, width));
        }
    }
}

 

이외에도 record 클래스에서 자동으로 생성하는 public 접근메서드나 equals(), hashCode(), toStrgin() 등을 구현할 수 있다. 이때 주의할 점은 메서드들의 타입과 매개변수 등이 자동으로 생성되는 메서드들과 동일해야한다.

3. Record 클래스 특징 

Record 클래스는 암시적으로 final 로 선언되기 때문에 다른 클래스를 상속받을 수 없으며 private final 이 아닌 인스턴스 필드를 선언할 수 없다. 하지만 그 외에 record 클래스가 Generic 클래스로 선언되거나, 다른 인터페이스를 구현 하는 등은 일반 클래스와 동일하게 가능하다.

 

static fields, static initializers, and static methods 도 구현할 수 있다. 이들은 일반 클래스에서와 동일하게 동작한다. 이외에도 instance method  nested class, interface 등도 바디에서 구현할 수 있다. 다만 static 이 아닌 instance fields  instance initializers 등은 구현할 수 없다.

[Reference]

- https://docs.oracle.com/en/java/javase/17/language/records.html

 

Java Language Updates

Record classes, which are a special kind of class, help to model plain data aggregates with less ceremony than normal classes.

docs.oracle.com

- https://colevelup.tistory.com/28

 

[Java] Java14 레코드(Record)를 알아보자

Java 8 , 11 버전만 사용하다 보니 이후 버전에 추가된 것들에 대해서 학습을 하려고 합니다. Java 14에서 추가된 레코드(Record)에 대해서 레코드의 목적, 자동생성 항목 등 레코드의 기본 사항에 대해

colevelup.tistory.com

 

 

반응형

'프로그래밍언어 > JAVA' 카테고리의 다른 글

[JAVA] Virtual Thread  (0) 2024.05.03
[JAVA] 람다식 (lambda expression)  (1) 2024.01.24
[JAVA] 자바 Thread-safe  (0) 2022.08.21
[JAVA] 메서드 참조 (::)  (0) 2022.04.14
[JAVA] 쓰레드의 동기화  (0) 2022.03.15