spotbugs / spotbugs

SpotBugs is FindBugs' successor. A tool for static analysis to look for bugs in Java code.

Home Page:https://spotbugs.github.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Still getting NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE with Objects.requireNonNull

cristalp opened this issue · comments

I have read the issues regarding Objects.requireNonNull, so I expected the following to show no errors (using Spotbugs Maven plugin 4.8.4.0 with Spotbugs 4.8.4).

package foobar;

import java.util.Objects;
import java.util.function.Supplier;

import javax.annotation.CheckForNull;
import javax.annotation.Nullable;

public class SpotBugsTest {

  public void foo() {
    final String foo = getString("foo");
    Objects.requireNonNull(foo);
  }

  public void bar() {
    final String bar = getString("bar");
    Objects.requireNonNull(bar, "Bar must not be null");
  }

  public void baz() {
    final Supplier<String> supplier = ()-> "Baz must not be null";
    final String baz = getString("baz");
    Objects.requireNonNull(baz, supplier);
  }

  @CheckForNull
  private String getString(@Nullable final String text) {
    return text == null ? null : text;
  }
}

However, I get Spotbugs errors for all three cases.

    <BugInstance type='NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE' priority='Normal' category='STYLE' message='Possible null pointer dereference in ch.ipi.schutztitel.bo.SpotBugsTest.bar() due to return value of called method' lineNumber='18' />
    <BugInstance type='NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE' priority='Normal' category='STYLE' message='Possible null pointer dereference in ch.ipi.schutztitel.bo.SpotBugsTest.baz() due to return value of called method' lineNumber='24' />
    <BugInstance type='NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE' priority='Normal' category='STYLE' message='Possible null pointer dereference in ch.ipi.schutztitel.bo.SpotBugsTest.foo() due to return value of called method' lineNumber='13' />

I thought this was fixed with the issues I read. Am I doing something wrong?

P.S. Thanks a lot for SpotBugs and carrying the load of work!

My understanding is that the methods are analysed separately, so when analyzing your foo, bar or baz methods SpotBugs is not smart enough to see that the calls to getString("xyz") won't return null. At the same time your code says that it can return null with @CheckForNull.

There recent change in #2709 was to let SpotBugs know that foo won't be null after Objects.requireNonNull(foo);