FindBugs & Reject.if* False Positives

In my current project we’re using Reject.if* (ifNull, ifNotNull, ifTrue…) methods for several validations, error management etc. As we’re also using FindBugs, we stumbled upon a problem with code like the following, in which FindBugs comes up with a NP_NULL_ON_SOME_PATH warning, in this case a false positive:

void foo(String bar) {
    Reject.ifNull(bar);
    bar.getBytes();
}

After searching for a solution and asking some people, we finally found a solution that works pretty well in this case: Passing a system property called findbugs.assertionmethods [1] through Maven to FindBugs. The code for it in the pom looks somewhat like this:

...
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>findbugs-maven-plugin</artifactId>
    <version>2.5</version>
    <configuration>
        <effort>Default</effort>
        <threshold>Medium</threshold>
        <xmlOutput>true</xmlOutput>
        <findbugsXmlOutputWithMessages>true</findbugsXmlOutputWithMessages>
        <omitVisitors>FindReturnRef</omitVisitors>
        <jvmArgs>-Dfindbugs.assertionmethods=de.mopri.utils.Reject.ifNull</jvmArgs>
    </configuration>
</plugin>
...

By using the jvmArgs element the system property is properly passed down to FindBugs and telling it that the method Reject.ifNull is used as an assertion. Now FindBugs acknowledges that bar.getBytes() won’t throw a NullPointerException :)

Leave a Reply