1. 개요
다음 프로젝트에서 본격적으로 사용해보기 위해 record를 정리한 내용이다.
2. Record?
오라클 공식 문서에 다음과 같이 기재되어 있다.
JDK 14 introduces records, which are a new kind of type declaration. Like an enum, a record is a restricted form of a class. It’s ideal for "plain data carriers," classes that contain data not meant to be altered and only the most fundamental methods such as constructors and accessors.
자바 14에서 추가된 문법으로, 변경되지 않을 데이터를 이동시킬 때 사용할 제한된 클래스이다. 이는 다음과 같은 기능을 제공한다
- 각 데이터에 private final 키워드를 추가한다.
- 각 데이터에 대한 getter, (public) constructor를 제공한다.
- equals, hashcode, toString 함수를 제공한다.
3. 구조 및 특징
package com.dbmodule.dto;
import com.dbmodule.domain.Post;
import java.util.Objects;
public final class PostDto {
private final String title;
private final String content;
public PostDto(
String title,
String content
) {
this.title = title;
this.content = content;
}
public PostDto(Post post) {
this(post.getTitle(), post.getContent());
}
public String title() {
return title;
}
public String content() {
return content;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj == null || obj.getClass() != this.getClass()) return false;
var that = (PostDto) obj;
return Objects.equals(this.title, that.title) &&
Objects.equals(this.content, that.content);
}
@Override
public int hashCode() {
return Objects.hash(title, content);
}
@Override
public String toString() {
return "PostDto[" +
"title=" + title + ", " +
"content=" + content + ']';
}
}
위 특징에 따라 위의 클래스를 아래와 같이 축약할 수 있다.
public record PostDto(
String title,
String content
) {
public PostDto(Post post) {
this(post.getTitle(), post.getContent());
}
}
헤더라 불리는 괄호 내부를 통해 컴파일러는 필드를 추론하여 컴파일 타임에 위 특징에서 명시한 함수들을 자동으로 생성한다. 바디라 불리는 가장 바깥쪽의 중괄호 안에서 멤버 함수를 정의할 수 있다.
String title = postReq.title();
record의 getter는 앞에 get을 붙이지 않고 사용한다.
4. 사용처?
db에서 데이터를 가져와 이동시킬 때, 이 데이터는 변하면 안된다. 이에 따라 record는 dto에 주로 사용될 수 있다. 변경되지 않는 데이터를 이동시켜야 할 때 record는 롬복 조차도 명시하지 않게 되어 적절히만 사용한다면 코드의 생산성을 향상시킬 수 있다.
'Java' 카테고리의 다른 글
[Java] BlockingQueue로 생산자-소비자 문제 해결하기 (0) | 2024.09.10 |
---|---|
[Java] 동시성 문제 해결하기 (0) | 2024.09.03 |
Java volatile - 메모리 가시성 (0) | 2024.08.29 |