Search code examples
nullpointerexceptionsonarqube

SonarQube warning about NPE even though null check is done


Why does Sq keep saying that the lines:

bankIdAuthenticationEntity.setOrderReference(authResponse.getBody().getOrderRef());
                    bankIdAuthenticationEntity.setAutoStartToken(authResponse.getBody().getAutoStartToken());

Can cause a NPE even after i check for it?

enter image description here


Solution

  • There are 2 cases:

    1st case: If getBody() method may return different (including null) results on consecutive calls then it may cause NPE.

    Try to extract the result of the first call into a variable like this:

    final BodyClass body = authResponse.getBody();
    if(body != null) {
        bankIdAuthenticationEntity.setOrderReference(body.getOrderRef());
        bankIdAuthenticationEntity.setAutoStartToken(body.getAutoStartToken());
    } else {
        // ...
    }
    

    2nd case is (mentioned in a comment by Luke Woodward) that both methods getOrderRef() and getAutoStartToken() may returned Integer/Long/Character which may be null.

    Then they need to be unboxed into int/long/char by the setOrderReference(...) and setAutoStartToken(...) methods which may cause NPE.