PMD bug with @SuppressWarnings annotation
PMD is an open source static analysis tool for the Java source code. It has a pretty good set of standard rules and you can add new rules by using XPath or Java code against the AST (Abstract Syntax Tree) it generates from the source code. The code analysis tools help you to keep your code clean and simple and avoid common pitfalls.
I recently found a bug while trying to analyze the code in the JDK 1.5 mode using PMD 3.8 version. The PMD seems to be ignoring all the violations for the class/method if you have a @SuppressWarnings annotation in it. According to the PMD documentation, only if you have @SuppressWarnings("") in your code, it’s supposed to ignore the violations for that class/method. But, the source code for PMD does not implement this logic. It just checks for the presence of @SuppressWarnings annotation and not any values passed to it. The end result is that all the violations are ignored. This can be very annoying as you may miss a significant number of violations.
To fix this issue, I made a couple of changes to the PMD source code. These are listed below with explanations:
-
net.sourceforge.pmd.ast.ASTAnnotation - This is the class where the check for
@SuppressWarningsis implemented. I made changes to the suppresses(Rule rule) method of this class to check if any values are passed to this annotation. If any values except""are passed (e.g.@SuppressWarnings("unchecked")), then all the PMD violations are written to the report. Otherwise if""is passed, all the PMD violations are suppressed. -
net.sourceforge.pmd.renderers.XMLRenderer - You need to change this only if you generate your PMD reports in the XML format. The changes I made here are to improve the information presented for suppressed violations tag (
<suppressedviolation>). So, if you decide to use the@SuppressWarnings("")annotation, at the end of reports their will be a section for suppressed violations. Another change I made is to enclose all the<suppressedviolation>tags inside a<file>tag for each file just like regular violations. -
net.sourceforge.pmd.util.StringUtil - This was throwing
NullPointerExceptionfor the suppressed violations while generating the report. I just added a null check here.
You can just replace the whole methods for ASTAnnotation and XMLRenderer classes and add the code snippet for StringUtil class. Once you do that you are ready to do the build. Run following in the bin directory of pmd-3.8 or the directory where you extracted the source code:
ant dist
That should create the pmd-3.8.jar in the lib directory. Now, you can use this jar whether you use the command line, ant or eclipse plugin to run PMD. If you have any questions, please leave me a comment.












