简体   繁体   中英

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 ?

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

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 :-)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM