How can I avoid the invalid pointer warning when the check is inside the method?

I am using the following method:

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

The problem is that it is not compatible with @Nullable. For istance in the following code, a warning appears when it should not.

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 saving isNullOrEmptyand Nullable?

+4
source share
2 answers

I think if you recycle a little for use Optional, you will 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 like:

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

Is there a reason you should not use if (o! = Null)?

Objects.isNull : .filter(:: IsNull)

. @SuppressWarnings, , .

+3

Source: https://habr.com/ru/post/1623241/


All Articles