Monday, March 19, 2012

Suppressing FindBugs warnings

Few days ago I spoke with my Friend, Tomek, about suppressing FindBugs warnings. Here is brief summary of our conversation, which may be interesting for you.

There is one simple method for suppressing the FindBugs warnings - usage of edu.umd.cs.findbugs.annotations.SuppressWarnings annotation. Just add it in place where FindBugs reported problem, and use appropriate bug code.

You should start with adding com.google.code.findbugs:annotations:2.0.0 jar to the project dependencies. Then open bug reported by FindBugs, and find its code, like in this example:


Finally add something like this to the method holding the code marked by FindBugs:


That's all, clear the FindBugs markers, and run it again, the problem will not be reported in this place again.

Nice! Isn't it? - No, it isn't :( - Why you may ask? - Because there is another annotation in java.lang package with exactly the same name (!), used for suppressing different kind of warnings. Shouldn't it be used instead? - Well ...

Another question is if we want to add another jar to the project dependencies just for suppressing FindBugs warnings - thank God the FindBugs authors marked this annotation with retention policy 'CLASS', which means the jar will not be required when running the project (ex. in web application container).


Follow-ups:


This article has been republished on Dzone's Javalobby (03/23/2012), with interesting comment from Fabrizio Giudici.

He is right that even RUNTIME retention doesn't require the jar itself, as long as the classes coming from it are not referenced directly, ex. if you have class A annotated with annotation B coming from some jar, and you don't include this jar in runtime classpath, using A.class.getAnnotation(B.class) will cause an error as expected (because class B is not available on classpath), while A.class.getAnnotations() will silently ignore B in this case.

See also Why doesn't a missing annotation cause a ClassNotFoundException at runtime?

2 comments:

  1. I think it's ok for having same name. But rather I have concerned that why compilation of my project need dependency of findbugs? Best way there should be any other approach like xml in which we can suppress warnings. In xml we can expect to suppress warning till method level. (Not line level :))

    ReplyDelete
  2. Thanks, very useful.

    My mistake was that findbugs could be suppressed by PMD suppression.

    So the following PMD supressions techniques didn't work:
    // NOPMD
    @supressWarnings("unused")
    @supressWarnings("PMD")
    @supressWarnings("PMD.NP_NONNULL_PARAM_VIOLATION")

    However the following does work:
    @SuppressWarnings("NP_NONNULL_PARAM_VIOLATION")

    ReplyDelete