Skip to content

아이템 11. equals를 재정의하려거든 hashCode도 재정의하라 #23

Answered by Irisation23
JoisFe asked this question in 3. 과제
Discussion options

You must be logged in to vote

@EqualsAndHashCode.Exclude, @EqualsAndHashCode.Include 저도 해당 어노테이션은 처음봐서 조금 더 찾아 봤습니다.

@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class Test {

    @EqualsAndHashCode.Include
    private int num1;
    private int num2;

    protected boolean canEqual(final Object other) {
        return other instanceof Test;
    }
}

@EqualsAndHashCode 해당 어노테이션의 default 값은 @EqualsAndHashCode(onlyExplicitlyIncluded = false) 입니다.
해당 경우는 클래스의 필드에 @EqualsAndHashCode.Include를 필드에 정의하지 않아도 핵심 필드로서 동작을 합니다.
하지만 위의 코드처럼 @EqualsAndHashCode(onlyExplicitlyIncluded = true) 값을 주게 된다면 반드시 핵심 필드를 @EqualsAndHashCode.Include로 정의 해주어야 한다는 사실을 알게 되었습니다.
Lombok이 굉장히 강력하네요.
앞으로 Lombok 어노테이션 사용할 때 상태 값으로 줄 수있는 경우…

Replies: 3 comments 3 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@JoisFe
Comment options

JoisFe Dec 26, 2022
Maintainer Author

Comment options

You must be logged in to vote
2 replies
@chikeem90
Comment options

@JoisFe
Comment options

JoisFe Dec 26, 2022
Maintainer Author

Answer selected by JoisFe
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
3장 모든 객체의 공통 메서드 이펙티브 자바 3장 (모든 객체의 공통 메서드)
3 participants