Suppressing warnings

Annotations

You can use a JDK 1.5 annotation to suppress PMD warnings, like this:

// This will suppress all the PMD warnings in this class
@SuppressWarnings("PMD")
public class Bar {
 void bar() {
  int foo;
 }
}

Or you can suppress one rule with an annotation like this:

// This will suppress UnusedLocalVariable warnings in this class
@SuppressWarnings("PMD.UnusedLocalVariable")
public class Bar {
 void bar() {
  int foo;
 }
}

PMD also obeys the JDK annotation @SuppressWarnings("unused"), which will apply to all rules in the unused ruleset

// This will suppress UnusedLocalVariable and UnusedPrivateMethod warnings in this class
@SuppressWarnings("unused")
public class Bar {
 void bar() {
  int foo;
 }
 private void foobar(){}
}

NOPMD

Alternatively, you can tell PMD to ignore a specific line by using the "NOPMD" marker, like this:

public class Bar {
 // 'bar' is accessed by a native method, so we want to suppress warnings for it
 private int bar; //NOPMD
}

You can use whatever text string you want to suppress warnings, for example, here's how to use TURN_OFF_WARNINGS as the suppressor:

$ cat Foo.java
public class Foo {
  void bar() {
    int x = 2; // TURN_OFF_WARNINGS
  }
}

$ ./pmd.sh Foo.java text unusedcode -excludemarker TURN_OFF_WARNINGS
No problems found!
UnusedLocalVariable rule violation suppressed by //NOPMD in /home/tom/pmd/pmd/bin/Foo.java

Note that PMD expects the //NOPMD marker to be on the same line as the violation. So, for example, if you want to suppress an "empty if statement" warning, you'll need to place it on the line containing the "if" keyword, e.g.:

$ cat ~/tmp/Foo.java
public class Foo {
 void bar() {
  int x = 42;
  if (x > 5) { // NOPMD
  }
 }
}
$ java net.sourceforge.pmd.PMD ~/tmp/Foo.java text basic
No problems found!
$

A message placed after the NOPMD marker will get placed in the report, e.g.:

public class Foo {
 void bar() {
  try {
    bar();
  } catch (FileNotFoundException e) {} // NOPMD - this surely will never happen
  }
 }
}

Suggestions? Comments? Post them here. Thanks!