Steven Solomon
Steven Solomon

Reputation: 301

Findbugs NP_ARGUMENT_MIGHT_BE_NULL not being triggered as expected

I am using Findbugs together with the annotation javax.annotation.Nonnull. In following method

@Nonnull
public String methodA(@Nonnull String foo, @Nonnull Integer bar) {
    // missing checkNotNull(foo)
    // missing checkNotNull(bar)
    
    int fooLen = foo.length();    // did not check that foo is non-null
    
    return (bar < fooLen)? foo : null; // did not check that bar is non-null
}

the params foo and bar are declared to be non-null, and they are subsequently dereferenced without first being checked if they are null. When I run Findbugs against the code (using the Gradle Findbugs plugin), the Findbugs report does not include the expected warning NP_ARGUMENT_MIGHT_BE_NULL. From the Findbugs website, the description of NP_ARGUMENT_MIGHT_BE_NULL:

NP: Method does not check for null argument (NP_ARGUMENT_MIGHT_BE_NULL)

A parameter to this method has been identified as a value that should always be checked to see whether or not it is null, but it is being dereferenced without a preceding null check.

What am I doing wrong?

Upvotes: 0

Views: 235

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

You've told findbugs that foo and bar are @Nonnull. This tells findbugs to look at invocations of methodA for the possibility of arguments being null and reject these if it finds them.

Within the method, precisely because they are annotated with @Nonnull, findbugs assumes they can't be null and therefore allows you to use them directly.

You might want to annotate the parameters with @CheckForNull for the behavior you expect.

Upvotes: 1

Related Questions