Tuesday, September 7, 2010

Suppress Findbugs warnings

Background:
Last week one colleague sent me an email to confirm a false warning from Findbugs. He explained it was SpringFramework init method, so need "Write to static field from instance method". As we know, it is a bad practice if multiple instances are manipulated. But here we need suppress the warning.

    public void setApplicationContext(ApplicationContext applicationContext) {
        context = (ApplicationContext) applicationContext;
        getServiceManager().getStatus().setSource(getServiceManagerUrl());
    }


Findbugs, PMD, Checkstyle, JTest and etc are popular static java code analysis tools. Findbugs uses bug detectors (pluggable) to analyze java bytecode (compiled class files) based on certain bug patterns. It self uses BCEL, ASM and dom4j etc open source libraries.

Installation:
Install Findbugs to Eclipse IDE is straightforward, and same as other Eclipse plugin. (Help -> Software Updates... -> Available Software -> Add Site using http://findbugs.cs.umd.edu/eclipse/). I use Findbugs-1.3.9 and JDK1.6 in the test of suppress code.

Run Findbugs:
After installation and restart Eclipse, in Package Explorer, right-click to find "Find Bugs" menu. We can configure to run Findbugs automatically.

Suppress Findbugs warning:
Unlike PMD leverages the @java.lang.SuppressWarnings annotation, or JTest uses predefined comments, Findbugs defines its own annotation in edu.umd.cs.findbugs package, so we need use below annotation

    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value =
        "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "Spring init method")
    public void setApplicationContext(ApplicationContext applicationContext) {
        context = (ApplicationContext) applicationContext;
        getServiceManager().getStatus().setSource(getServiceManagerUrl());
    }


or

    import edu.umd.cs.findbugs.annotations.SuppressWarnings
    @SuppressWarnings(value =
        "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification = "Spring init method")
    public void setApplicationContext(ApplicationContext applicationContext) {
        context = (ApplicationContext) applicationContext;
        getServiceManager().getStatus().setSource(getServiceManagerUrl());
    }


Reference:
http://findbugs.sourceforge.net/manual/eclipse.html
http://findbugs.sourceforge.net/manual/annotations.html

2 comments:

  1. Any idea on how to suppress more than ont findbug warning?
    I tried with
    @edu.umd.cs.findbugs.annotations.SuppressWarnings(value ="{ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD},{NP_LOAD_OF_KNOWN_NULL_VALUE}", justification = "Spring init method")



    But that did not work....

    ReplyDelete
    Replies
    1. Use {"", "", ""}

      @edu.umd.cs.findbugs.annotations.SuppressWarnings(value ={"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD","NP_LOAD_OF_KNOWN_NULL_VALUE"}, justification = "Spring init method")

      Delete