Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Still getting NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE with Objects.requireNonNull #2965

Open
cristalp opened this issue Apr 23, 2024 · 1 comment

Comments

@cristalp
Copy link

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!

@gtoison
Copy link
Contributor

gtoison commented May 28, 2024

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);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants