Java Rule ‘Null pointers should not be dereferenced’
I’m getting this fault in the next code when obj can’t be null in any scenario. Seems the analizer don’t recognice the logic with the funcional object Optional.
final Obj obj = Optional.ofNullable(oldObj).orElse(new Obj());
Hi,
I struggle to understand where the issue is raised exactly, could you specify more precisely where the issue is raised (and so which object is assumed to be null) ? Is your sonarlint using connected mode ?
...
registrarEvento010Enviado(proceso, fraEnvio010, fechaGeneracion); // The sonar fault is marked in this line.
}
}
private void registrarEvento010Enviado(final Proceso proceso, final FraEnvio010 envio010,
final LocalDateTime fecGeneracion) {
final FraEnvio010 fraEnvio010 = Optional.ofNullable(envio010).orElse(new FraEnvio010());
if (fraEnvio010.getFraEnvioPK() == null) { // This access cause the sonar fault. But, is impossible to produce a NullPointer
fraEnvio010.setFraEnvioPK(new FraEnvioPK());
}
...
// Alternative to Optional and without sonar fault:
//
// FraEnvio010 fraEnvio010;
//
// if (Objects.isNull(envio010)) {
// fraEnvio010 = new FraEnvio010();
// } else {
// fraEnvio010 = envio010;
// }
May be is better understable reading real code. At the end, sonar advise me that the use of this function will throw a null pointer. But, is imposible to happend.
I really struggle to understand the issue you are facing given how the rule is supposed to be working.
Could you share a small screenshot of the issue ? Are you using latest version of sonarlint ? if in connected mode what’s the version of sonarjava on your server ?
Closing the topic for lack of traction. If you are still experiencing a similar problem. Please open a new thread with a clear, self-contained, compiling reproducer, and the version of SonarQube and Analyzer for Java you are using.