NullPointerException with already done checks

Hi all.
I have a interesting code block and an error from SonarLint -
Bug, Major, java:S2259: Null pointers should not be dereferenced.

And here is a method:

public DataType extract(final CloudEvent cloudEvent) {
        if (cloudEvent == null) {
            LOG.warn("Can't process message because message is null");
            return null;
        if (cloudEvent.getData() == null) {
            LOG.warn("Can't process message because data part is not set.");
            return null;
        if (!(cloudEvent.getData() instanceof JsonCloudEventData)) {
            LOG.warn("Can't process message because message format is not correct. "
                    + "JsonCloudEventData expected and {} received.",
            return null;
// Rest of logic

SonarLint shows the issue here - cloudEvent.getData().getClass().
Method getData() has @Nullable annotation. And, as you can see, there are plenty of checks for null value.

Interesting is when even I rewrite the issued part like this -

cloudEvent.getData() != null 
? cloudEvent.getData().getClass().getName() 
: "Empty Message"

it still shows the bug in here.
Could somebody please explain why null-pointer rule is ignoring all previous checks?
Thanks in advance.


Welcome to the community!

What version of SonarLint are you using? Are you in connected mode with SonarCloud or SonarQube? And if the latter, which version?


Hello @IDnew,

You access cloudEvent.getData() several times in this method. SonarLint cannot be sure if the value returned by this method is always the same or changes between calls (could be changed by another thread for example). That’s why the issue is raised.

The easy workaround is to store the value in a local variable, with your last example:

var data = cloudEvent.getData();
message = data != null 
? data.getClass().getName() 
: "Empty Message";
1 Like

Hi G Ann.
Sorry for the late answer.
I’m using SonarLint v. 8.0.63273.
I’m not connected to the SonarCloud or SonarQube.

HI Damien.

Thanks for the tip.
You’ve right -there could be a possibility of changing value between calls in multi-threading surface.
This method is called in the rxJava stream, so it should be thread-save, but I don’t think that SonarLint could scan so far.

And yes - your solution is really simple and more elegant then mine -

String wrongMessageFormat = Optional.of(cloudEvent.getData()).get().getClass().getName();

Thanks for the explanation.
Topic is closed.
Best regards :slightly_smiling_face:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.