• Maintainable HashCode and Equals Using Apache Commons


    Java hashCode and equals methods can be tricky to implement correctly. Fortunately, all majors IDEs allow generating them. For example, this is how they look like for a class with two attributes when generated in Eclipse:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
        return result;
    }
     
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        if (lastName == null) {
            if (other.lastName != null)
                return false;
        } else if (!lastName.equals(other.lastName))
             return false;
        return true;
    }

    It’s better than writing all this by hand but I still don’t like it. Here’s why:

    • It makes it way too easy to forget about updating them after adding a new field
    • It lowers the code coverage when not properly tested
    • It is just plain ugly

    The first reason is the most important one. Having to remember about updating generated equals and hashCode methods when adding new fields increases the maintenance cost. Forgetting to do so may result in nasty bugs.

    Because of that I never use generated hashCode and equals. I use builders from Apache Commons instead. In the most basic scenario they look like this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @Override
    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }
     
    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }

    They retrieve values using reflection from all fields except for transient and static ones. Most of the time this is precisely what I want. If you need some customizations check out the API documentation.

  • 相关阅读:
    c 中有关打印*,字符的题目集
    c 求两个整数的最大公约数和最小公倍数
    cygwin中vim的使用方法
    window下如何搭建linux环境
    ORA-00923: 未找到要求的 FROM 关键字
    c# datagridviewcomboboxcell值无效的解决办法
    sql substring charindex
    C# 中datagridview行里面有三个cheeckbox,要控制成三选一。
    程序中使用事务来管理sql语句的执行,执行失败时,可以达到回滚的要求。
    WinForm界面中快捷键设置
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3585726.html
Copyright © 2020-2023  润新知