False Positive: Rule java:S8696 flags standard java.time enums (DayOfWeek, Month, ChronoUnit)

What language is this for?

Java

Which rule?

java:S8696 (“Reference equality should not be used with value-based classes”)

Why do you believe it’s a false-positive?

The rule triggers a false positive when comparing standard JDK enums from the java.time package space using == or !=. Comparing enums with identity operators is correct, type-safe, and recommended Java practice (per Effective Java guidelines).

The issue seems to be from the analyser’s implementation of TypeUtils.isValueBasedType. It relies on a regex pattern (JAVA_TIME_PACKAGE_PATTERN) that matches the entire java.time.* name-space, without validating if the type is explicitly an enum (type.isEnum()):

if (type.isUnknown() || type.is(JAVA_TIME_CLOCK)) {
  return false;
}
return type.isPrimitiveWrapper() || VALUE_BASED_TYPES.stream().anyMatch(type::is)
    || JAVA_TIME_PACKAGE_PATTERN.matcher(type.fullyQualifiedName()).matches();

Because of this enums like java.time.DayOfWeek, java.time.Month, and java.time.temporal.ChronoUnit are incorrectly flagged as value-based types when identity operators are applied.

How can we reproduce the problem?

import java.time.DayOfWeek;
import java.time.LocalDate;

public class SonarEnumBug {
    public boolean isNotSaturday(LocalDate day) {
        // Flags java:S8696 here even though DayOfWeek is a true enum
        return day.getDayOfWeek() != DayOfWeek.SATURDAY; 
    }
}

Proposed Contribution

I have isolated the logic flaw in TypeUtils.isValueBasedType and am prepared to submit a PR to fix it if this is accepted as an underlying analyzer bug.

1 Like