Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get checkstyle to skip equals() and hashcode() methods generated by eclipse?

Our project contains several classes that we have equals() and hashCode() methods generated by Eclipse (Right Click -> Source -> Generate hashCode() and equals()).

Example:

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    final MyTO other = (MyTO) obj;
    if (num != other.num)
        return false;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    if (table == null) {
        if (other.table != null)
            return false;
    } else if (!table.equals(other.table))
        return false;
    return true;
}

These methods that work well for our application, but unfortunately do not pass our cyclomatic complexity checks with Checkstyle. Since these methods are auto-generated, we are not concerned with their complexity. We could suppress the entire class from Checkstyle, but we would prefer to be able to exclude just these two methods.

Does anyone know how to create a custom rule in Checkstyle that will allow us to exclude generated equals() and hashCode() methods in any way, without excluding the entire class?

like image 836
Brent Avatar asked Nov 11 '10 19:11

Brent


People also ask

Which class does override the equals () and hashCode () methods?

All wrapper classes and String class overrides the equals() and hashCode().

Can we override hashCode method in Java?

So all java classes have the hashcode() method by default. We can override these methods in our classes. Hashcode() is a method to return an unique integer which is used for indentifying the bucket where this object will be stored for hashing based collections like HashMap.


1 Answers

You should set up a SupressionCommentFilter. More info on this here.

Sometimes there are legitimate reasons for violating a check. When this is a matter of the code in question and not personal preference, the best place to override the policy is in the code itself. Semi-structured comments can be associated with the check.

like image 108
mgv Avatar answered Oct 07 '22 15:10

mgv