개발을 잘하고 싶은 개발자

[Java] 끝판왕 @Data 를 아시나요? 본문

Backend/Java

[Java] 끝판왕 @Data 를 아시나요?

_소피아 2021. 8. 10. 23:36

출처 : https://www.daleseo.com/lombok-popular-annotations/#%EB%81%9D%ED%8C%90%EC%99%95-data

 

[자바] 자주 사용되는 Lombok 어노테이션

Engineering Blog by Dale Seo

www.daleseo.com

@Data는 위에서 설명드린 @Getter, @Setter, @RequiredArgsConstructor, @ToString, @EqualsAndHashCode을 한꺼번에 설정해주는 매우 유용한 어노테이션입니다. 무려 이 6가지를 한 어노테이션에 다!!

클래스 레벨에서 "@Data" 어노테이션만 붙여주면, 모든 필드를 대상으로 접근자와 설정자가 자동으로 생성되고, final 또는 @NonNull 필드 값을 파라미터로 받는 생성자가 만들어지며, toStirng, equals, hashCode 메소드가 자동으로 만들어집니다.

@Data
public class Example {
    private String name;
    private double score;
}


// lombok annotation 미사용

public class Example {
    private String name;
    private double score;

    public DataExample(String name) {
        this.name = name;
    }
  
    public String getName() {
        return this.name;
    }
  
    public void setScore(double score) {
        this.score = score;
    }
  
    public double getScore() {
        return this.score;
    }
  
    @Override public String toString() {
        return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + ")";
    }
  
  protected boolean canEqual(Object other) {
    return other instanceof DataExample;
  }
  
  @Override public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof DataExample)) return false;
    DataExample other = (DataExample) o;
    if (!other.canEqual((Object)this)) return false;
    if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
    if (this.getAge() != other.getAge()) return false;
    if (Double.compare(this.getScore(), other.getScore()) != 0) return false;
    if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false;
    return true;
  }
  
  @Override public int hashCode() {
    final int PRIME = 59;
    int result = 1;
    final long temp1 = Double.doubleToLongBits(this.getScore());
    result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
    result = (result*PRIME) + this.getAge();
    result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
    result = (result*PRIME) + Arrays.deepHashCode(this.getTags());
    return result;
   }
  }

 정말 대단하지 않나요??