merours
merours

Reputation: 4106

How can I avoid null pointer access warning when the check is inside a method?

I dispose of the following method :

boolean isNullOrEmpty(String s) {
  return s == null || s.length() == 0;
}

Trouble is, it isn't compatible with @Nullable. For istance, in the following code, a warning is displayed when it shouldn't.

void test(@Nullable String s) {
  if (!isNullOrEmpty(s)) {
    s.length(); // warning : o may be null
  }
}

Is there a way to make this warning go away while conserving isNullOrEmpty and Nullable ?

Upvotes: 4

Views: 234

Answers (2)

Erick G. Hagstrom
Erick G. Hagstrom

Reputation: 4945

I think if you refactored a bit to use Optional you'd be better off.

@NonNull Optional<String> optNullOrEmpty(@Nullable String s) {
  if (s == null || s.length() == 0)
    return Optional.empty();
  else
    return Optional.of(s);
}

Then you can use it as:

void test(@Nullable String s) {
  @NonNull Optional<String> os = optNullOrEmpty(s);
  if (os.isPresent()) {
    @NonNull String s1 = os.get();
    s1.length(); // No warning :-)
  }
}

Upvotes: 2

Remi
Remi

Reputation: 151

Is there a reason for you not to use if (o != null) ?

The purpose of Objects.isNull is to be used as a predicate : .filter(Objects::isNull)

This warning might be a bug though. You can annotate your method with @SuppressWarnings if you really want it to go away

Upvotes: 3

Related Questions