JetBrains @Contract using field

I have the following class *:

public class MyClass {

  @Nullable
  private String mString;

  /* ... */

  public boolean contains(@NotNull final String text) {
    if(!isNullOrEmpty()) {
      return mString.contains(text);
    } else {
      return false;
    }
  }

  public boolean isNullOrEmpty() {
      return mString == null || mString.isEmpty();
  }
}

Now mString.contains(text)IntelliJ warns me what mStringcould be null, although it is guaranteed that it is not. I noticed that JetBrains has annotation @Contract. Is there a way that I can annotate isNullOrEmpty()in such a way that I do not receive this warning when the method returns true?

I hope the annotation comes @Contractcloser to the Java Modeling Language , for example:

//@ ensure \result == true ==> mString != null;
public boolean isNullOrEmpty() {
  return mString == null || mString.isEmpty();
}

In addition, I would like to be isNullOrEmpty()left without parameters, as it is part of the public API.

* Just a fictional class for demo purposes :) Actual code uses a more complex class.

+4
3

mString , 'isNullOrEmpty' < mString.contains ' mString. , @Contract . @Contract, isNullOrEmpty:

public isNullOrEmpty(String pString) {}
+7

, mString @Nullable, mString null. ; , null, IntelliJ .

, @Nullable. , @NotNull?

, contains, IntelliJ ; , mString == null, .

: @Contract . - , - ( @Nullable, @NonNull, @MagicConstant ..).

+2

@Contract , , , isNull :

@Contract("null -> true; !null -> false")
private boolean isNull(String value) {
  return value == null;
}

:

  public boolean contains(@NotNull final String text) {
    if(!isNull(text)) {
      return mString.contains(text);
    } else {
      return false;
    }
  }

, :

  public boolean contains(@NotNull final String text) {
    if(text != null) {
      return mString.contains(text);
    } else {
      return false;
    }
  }
0

All Articles