polygenelubricants
polygenelubricants

Reputation: 383856

How do I use @CheckForNull etc with Findbugs?

When I run this through Findbugs, I get a warning:

static @NonNull Object foo(@CheckForNull Object arg) {
    if (arg == null) { // warning on this line
        throw new NullPointerException();
    }
    return "something";

}

The details of the warning is the following:

Bug: arg must be nonnull but is marked as nullable
Pattern id: NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE, type: NP, category: STYLE

This parameter is always used in a way that requires it to be nonnull, but the parameter is explicitly annotated as being Nullable. Either the use of the parameter or the annotation is wrong.

Can someone explain what Findbugs is complaining about here?

Note that I'm using the edu.umd.cs.findbugs.annotations.* members, not the javax.annotations.*. (Is there a difference?)

Set up is FindBugs plug-in 1.3.9.2009- for Eclipse 3.6.1.


Matthew Flaschen suggested that I use @NonNull instead, but now I ran into this problem:

static void blah(@NonNull Object arg) {
    if (arg == null) {
        throw new NullPointerException();
    }
    System.out.println(arg);
}

static @CheckForNull Object bleh() {
    return null;
}

//...
blah(bleh()); // warning here!

The details of the warning is:

Bug: Possible null pointer dereference due to return value of called method
Pattern id: NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE, type: NP, category: STYLE

The return value from a method is dereferenced without a null check, and the return value of that method is one that should generally be checked for null. This may lead to a NullPointerException when the code is executed.

I basically want blah to satisfy the @CheckForNull requirement, but I can't do it if I make its arg be @NonNull. How do I get this to work?

Upvotes: 1

Views: 4365

Answers (1)

Matthew Flaschen
Matthew Flaschen

Reputation: 284927

You're contradicting yourself. CheckForNull means, "The annotated element might be null", but if it is you immediately throw.

If it's never acceptable for a caller to pass null, I believe you should instead annotate it:

static @NonNull Object foo(@NonNull Object arg) {

Upvotes: 5

Related Questions