How to activate warnings for possible return of NULL when method has @Nonnull anotation for return value

已回答

When I do return some unchecked value in a method which has @Nonnull, and this value is the return of method which does not specify an annotation, I expect a warning that this may return null, as it does if the other method has @Nullable annotation.
How do achieve that?

Sample:

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class Sample {
  public String nullOrNotNull() {
    return null;
  }

  public @Nullable String nullable() {
    return null;
  }

  public @Nonnull String returnNullable() {
    return nullable();
  }

  public @Nonnull String returnNullOrNonNull() {
    return nullOrNotNull();
  }
}


return nullable(); gets the warning, but not return nullOrNotNull();

0

Hi, Mbrach !

Thank you for reaching out to us! My apologies for the delay in getting back to you.

By default, the IDE only issues a warning when you return a value from a method annotated as @Nullable into a method annotated as @Nonnull. If the returned method is unannotated (like nullOrNotNull()), IntelliJ does not warn you—even if it actually returns null—because it treats unannotated methods as "unknown" rather than explicitly nullable. I'm afraid that the only workaround I can suggest to you right now is to consider annotating all methods that may return null with @Nullable, so the inspection can catch these cases.

Let me know if you have any questions on the way.

0

Gabriel Cataneo: Problem here is that I need this behavior for methods out of my control. For My own methods I always set the annotations accordingly. 
But when I call methods from libraries which are not annotated I cannot be sure if they are annotated or not and to check it manually every time I call some method is quite unnerving…

I hoped to have overlooked something or it would be possible to at least specify a custom inspection to achieve that but this does not seem to be possible either :/ 

0

Hello Mbrach, thanks for your update.

In this case you can try to use External annotations and set via them @NotNull annotations to the necessary methods.
If this doesn't suit you, please elaborate on how you see a useful function for the situation you described. We could create a feature request. Thank you!

0

请先登录再写评论。