S2259: False positive when comparing to class

Hi,

when checking an instance for null and later comparing with a class SonarJava incorrectly reports a possible null dereference:

public class S2259 {

  public <T> T getAdapter(Class<T> adapter) {
    if (adapter != null && adapter.isInstance(this)) {
      return adapter.cast(this);
    } else if (adapter == String.class) {
      return adapter.cast("");
          // ^^^^^^^
          // reports adapter is nullable here
    }

    return null;
  }
}

Issue flow is reported as
grafik
adapter is not null in the second branch as comparison to String.class would yield false.

Issue is present in both SonarLint and SonarQube; version are:
SonarLint: 5.9.0
SonarQube: 8.9.0 LTS

Hey @oliver,

Thanks for bringing this up to us.
Indeed, this is a reproducible false positive and a ticket has been created to handle the issue.

Dorian

1 Like