Java

[Java] Record

비번변경 2026. 3. 23. 10:46

Record

Java 14 버전에서 도입된 클래스 타입으로 변경 불가(immuatable) 데이터 객체를 만드는 기능을 제공한다. 기존 클래스와 비슷하지만 더 간결하게 데이터 객체를 만들 수 있다.

 

 

특징

Record 클래스는 다음과 같은 특징을 가지고 있다.

 

- 간결성 : 간결한 코드를 작성하기 위해 도입되어, 정의한 필드를 기반으로 메서드가 자동 생성된다. 코드의 양을 줄임으로써 가독성을 확보한다.

- 메서드 자동 생성 : 필드를 기반으로 equals, hashCode, toString, getter을 자동 생성하여 반복적인 코드 작성을 피한다.

- 불변성 : 필드가 설정되면 값을 변경하지 못하여 데이터 안정성을 높인다.

- final 생략 : 필드를 불변으로 취급하기 때문에 자동으로 final 처리를 한다.

- 패턴 매칭 : 패턴 매칭을 사용해 데이터 추출 및 일치 검사에 효과적이다.

- 데이터 전달 : Record의 주된 목적은 불변 데이터를 전달하는 것으로 DTO(Data Transfer Object)를 표현하기에 적합한다.

 

 

사용 예시

예로 들어 아래와 같은 User를 표현하는 DTO가 있다고 하자.

// User.java
public final class User {
    private final Long id;
    private final String email;
    private final String name;

    public User(Long id, String email, String name) {
        this.id = id;
        this.email = email;
        this.name = name;
    }

    public Long getId() {
        return id;
    }

    public String getEmail() {
        return email;
    }

    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User user)) return false;
        return id.equals(user.id) && email.equals(user.email) && name.equals(user.name);
    }

    @Override
    public int hashCode() {
        return java.util.Objects.hash(id, email, name);
    }

    @Override
    public String toString() {
        return "User{" + "id=" + id + ", email='" + email + '\'' + ", name='" + name + '\'' + '}';
    }
}
// Main.java
public class Main {
    public static void main(String[] args) {
        User user = new User(1L, "passwd@tistorycom", "user1");
        System.out.println(user);
    }
}

이 User 클래스를 record를 활용하여 작성하면 아래와 같이 작성할 수 있다.

// User.java
public record User(
        Long id,
        String email,
        String name
) {

}

다만 getter는 getVarName 형식이 아닌 변수명으로 생성된다.

public class Main {
    public static void main(String[] args) {
        User user = new User(1L, "passwd@tistorycom", "user1");
        System.out.println(user.id());
    }
}

 

참고 문서

https://s7won.tistory.com/2

https://m.blog.naver.com/seek316/223341255150

 

 

728x90