Lombok @EqualsAndHashCode 的用法


  1. 此注解會生成equals(Object other) 和 hashCode()方法。
  2. 它默認使用非靜態,非瞬態的屬性
  3. 可通過參數exclude排除一些屬性
  4. 可通過參數of指定僅使用哪些屬性
  5. 它默認僅使用該類中定義的屬性且不調用父類的方法

當啟動@EqualsAndHashCode時,默認不調用父類的equals方法,當做類型相等判斷時,會遇到麻煩,例如:

@Data
public class People {
    private Integer id;
}

@Data
public class User extends People {
    private String name;
    private Integer age;
}

public static void main(String[] args) {
    User user1 = new User();
    user1.setName("jiangxp");
    user1.setAge(18);
    user1.setId(1);

    User user2 = new User();
    user2.setName("jiangxp");
    user2.setAge(18);
    user2.setId(2);

    System.out.println(user1.equals(user2));
}

輸出結果:true

注意:兩條user數據,ID完全不一樣,結果明顯是錯的,沒有做id的equals判斷

需要將@EqualsAndHashCode修改為@EqualsAndHashCode(callSuper = true)才能得到正確結果.
反編譯修改后的User.class,發現有些許變化

public boolean equals(Object o) {
    if (o == this) {
        return true;
    } else if (!(o instanceof User)) {
        return false;
    } else {
        User other = (User)o;
        if (!other.canEqual(this)) {
            return false;
        } else if (!super.equals(o)) {    // (1)此處變化,調用了父類的equals,原:無此段邏輯
            return false;
        } else {
            Object this$name = this.getName();
            Object other$name = other.getName();
            if (this$name == null) {
                if (other$name != null) {
                    return false;
                }
            } else if (!this$name.equals(other$name)) {
                return false;
            }

            Object this$age = this.getAge();
            Object other$age = other.getAge();
            if (this$age == null) {
                if (other$age != null) {
                    return false;
                }
            } else if (!this$age.equals(other$age)) {
                return false;
            }

            return true;
        }
    }
}

 public int hashCode() {
    int PRIME = true;
    int result = super.hashCode(); //(2)此處變化,調用了父類的hashCode(); 原:int result = 1;
    Object $name = this.getName();
    result = result * 59 + ($name == null ? 43 : $name.hashCode());
    Object $age = this.getAge();
    result = result * 59 + ($age == null ? 43 : $age.hashCode());
    return result;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM