java:S2097 false positive

  • Operating system: Windows 11
  • SonarQube for IntelliJ plugin version: 11.6.0.83783
  • IntelliJ version: 2025.2.5
  • Programming language you’re coding in: Java 17
  • Is connected mode used:
    • Yes, SonarQube server

When the syntax of effective class typing is switched in a Hibernate entity’s equals() method, Sonar is no longer able to parse the code as type checking the object before attempting to cast it.

Here I provide code snippets in the equals() method for the EntityClass class.

Offending example:

Class<?> oEffectiveClass = o instanceof HibernateProxy hibernateProxy ? hibernateProxy.getHibernateLazyInitializer().getPersistentClass() : o.getClass();
Class<?> thisEffectiveClass = this instanceof HibernateProxy hibernateProxy ? hibernateProxy.getHibernateLazyInitializer().getPersistentClass() : this.getClass();
if (thisEffectiveClass != oEffectiveClass) return false;
EntityClass that = (EntityClass) o; // offending line, raises rule at method level

Example without false positive, slightly altered syntax:

Class<?> oEffectiveClass = o instanceof HibernateProxy ? ((HibernateProxy) o).getHibernateLazyInitializer().getPersistentClass() : o.getClass();
Class<?> thisEffectiveClass = this instanceof HibernateProxy ? ((HibernateProxy) this).getHibernateLazyInitializer().getPersistentClass() : this.getClass();
if (thisEffectiveClass != oEffectiveClass) return false;
EntityClass that = (EntityClass) o; // sonar has no issues with this cast

Hello Daniel,

thank you for reporting this issue!
Unfortunately, I have some trouble reproducing the issue on my end.

Would it be possible for you to share a minimal reproducer example that includes the entire class?
(Even better if it also includes your build configuration, e.g. your maven pom.xml or Gradle build files including the versions of your dependencies etc.)