18

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?

Brent
  • 183
  • 3
  • 5

1 Answers1

5

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.

mgv
  • 8,384
  • 3
  • 43
  • 47
  • I'm not that familiar with SupressionFilters. How would I determine what line numbers to exclude for each file based on, say, the method name? – Brent Nov 11 '10 at 20:01
  • Looks like a [`SuppressionCommentFilter`](http://checkstyle.sourceforge.net/config.html#SuppressionCommentFilter) (from that same link) is what's needed. It even includes an example of exluding generated code. – matt Nov 11 '10 at 20:01
  • Yup matt, i confused'em :). Edited in the answer. Ty – mgv Nov 11 '10 at 20:02
  • Ah. While not the ideal solution (I now will need to go back and add comments to each file with generated code, and remember to do this in the future), this seems like it will work. Thanks. – Brent Nov 11 '10 at 20:05
  • It's far from being ideal, but I don't think you have any other option right now :( – mgv Nov 11 '10 at 20:10
  • does any one have example for such config? – Maciej Miklas Jan 03 '12 at 10:08
  • See http://stackoverflow.com/questions/4023185/how-to-disable-a-particular-checkstyle-rule-for-a-particular-line-of-code/4023351#4023351 for example code on suppressing checkstyle findings. – Chris Knight Jan 31 '14 at 10:01