Skip to content
Advertisement

Sonar Issue-Possible null pointer dereference due to return value of called method. Return value from a method is dereferenced without a null check

I have a void method which is being called with a string argument from a parent method.

private void sendMail(String msg) {
     SimpleMailMessage message = null;
     try {
        SimpleMailMessage templateMessage = mailSender.getSimpleMailMessage();
        if(templateMessage != null ) {
            message = new SimpleMailMessage(templateMessage);
            if(message != null) {
                if(templateMessage.getSubject() != null) {
                    message.setSubject(String.format(templateMessage.getSubject(), System.getProperty("env")));
                }
                if(templateMessage.getText() != null) {
                    message.setText(String.format(templateMessage.getText(), msg)); // This line of code is throwing Sonar issue
                }
            }
        }
    }
}

Advertisement

Answer

String text = templateMessage.getText();
if (text != null) {
   message.setText(String.format(text, msg));
}

getText seems to be more than a simple getter. The second time it evidently may return null.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement