Thursday, July 10, 2008

SuppressWarning

We check our codebase against a custom set of PMD rules, but sometimes we'd like to ignore of some of them, tipically for IDE-generated code (e.g. hashCode ) or when overriding methods (e.g. methods throwing raw exceptions).

The best possibility we've found is tied to the built-in SuppressWarnings annotations you get in Java 5: if you want to ignore all PMD warnings for the hashCode method you simply have to add the line

@SuppressWarnings("PMD")

before your method. If you want to exclude a specific rule you can use the syntax

@SuppressWarnings("PMD.SignatureDeclareThrowsException")

while for more than a rule the line gets something like

@SuppressWarnings({"PMD.LongVariable", "PMD.DefaultPackage"})

The annotation can be applied to all the available levels: class, constructor, field, method, local variable, and so on and so forth.

You could also add the (customizable) comment //NOPMD on the same line for which you experience the warning, but it is much less elegant and powerful.

No comments: