record란?
데이터 저장 목적 객체를 간단하게 만들기 위한 Java 문법
(자바 16부터 정식 지원)
record가 자동 생성하는 것
- 생성자
- gettrt 비슷한 메서드 (기존 getter와 이름이 다르다. getId()가 아닌 id(). 즉, 필드명이 메서드 이름)
- toString()
- equals()
- hashCode()
특징
가장 큰 특징은 불편(immutable). 그렇기 때문에 생성 후 변경 위험이 적으면 좋은 DTO에 많이 쓰인다.
record의 장점
- 코드 짧아짐
- 가독성 증가 (DTO 의도 표현 명확)
- 불변 객체 (안정성 증가)
예시
public class ProductResponse {
private final Long id;
private final String name;
private final int price;
public ProductResponse(Long id, String name, int price) {
this.id = id;
this.name = name;
this.price = price;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
}
위 코드를 record를 사용하여 아래와 같이 변경
public record ProductResponse(
Long id,
String name,
int price
) {
}
'Java > 기본 문법' 카테고리의 다른 글
| 람다(Lambda) (0) | 2026.05.21 |
|---|---|
| 제네릭(Generic) (0) | 2026.05.20 |
| Collection (0) | 2026.05.20 |
| Optional (0) | 2026.05.20 |
| 예외(Exception)와 예외 처리(try-catch) (0) | 2026.05.20 |