Aaron Digulla
Aaron Digulla

Reputation: 328724

How do I mark a method as "afterwards, parameter X cannot be null"?

I have this method:

 @Override
 public void foo( @Nullable Bar bar ) {
     Validate.notNull( bar, "bar is null" );
     bar.x();
 }

Since the method is defined elsewhere, I can't mark bar with @NotNull. The call to Validate.notNull() will make sure that bar isn't null but of course FindBugs and similar tools don't know anything about this constraint.

Is there a simple way to teach FindBugs that, after the call to Validate.notNull(), bar must be not null?

With simple, I mean a way where I have to define this in one place; of course, I could sprinkle my code with millions of @SuppressWarnings... :-)

Upvotes: 2

Views: 119

Answers (1)

TimK
TimK

Reputation: 4835

Change Validate.notNull to return the reference, marking its return value as @NotNull:

@NotNull
public static <T> T notNull(@Nullable T reference, String message) {
    if (reference == null) {
        throw new NullPointerException(message);
    }
    return reference;
}

Then use the result of the notNull call instead of the original parameter value:

public void foo(@Nullable Bar bar) {
    bar = Validate.notNull(bar, "bar is null");
    bar.x();
}

Upvotes: 1

Related Questions