Have a problem with SpotBugs "Possible null pointer dereference due to return value of called method (NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE)".
With Lombok getter:
@Generated
public @Nullable Integer getPort() {
return this.port;
}
When i try to get value from object using getPort() and produce it to another method where it can't be null spotbugs shows an error "NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE" in strange cases.
Example 1.
Ok here a value possible null.
session.connectAndBind(gateway.getHost(), gateway.getPort()); // <--- Error
Example 2.
Get same error on unboxing.
int port = gateway.getPort() != null ? gateway.getPort() : 0; // <--- Error
session.connectAndBind(gateway.getHost(), port);
Example 3.
Still get error on unboxing.
int port = 0;
if (gateway.getPort() != null) { // <--- Error
port = gateway.getPort();
}
session.connectAndBind(gateway.getHost(), port);
So why i getting the error?
Find one case when veryfi pass with no errors. Code below.
// Pass
Integer port1 = gateway.getPort();
int port = port1 != null ? port1 : 0;
session.connectAndBind(gateway.getHost(), port);
Example 1: connectAndBind
probably takes an int
, not an Integer
, so Spotbugs is correct.
Example 2 & 3: Spotbugs doesn't know that both gateway.getPort()
invocations return the same value. Fix it by using Integer port = gateway.getPort();
, a null check, then just port
everywhere else, and the warning should go away. That's basically what you've done in your last example.