java:S2333 false positive when @SafeVarargs annotation requires method to be final

Hi

Environment

Java 17 (Java version: 17.0.5, vendor: Eclipse Adoptium, runtime: jdk-17.0.5.8-hotspot). SonarQube Developer Edition Version 10.0 (build 68432) + SonarLint 8.3.0.71062 in IntelliJ, in connected mode. Rule is java:S2333.

Example code

Consider a class like the following:

public final class Example<C extends Comparable<C>> {

    @SafeVarargs
    public final Example<C> foo(C... elements) {
        return this;
    }
}

One would want to add @SafeVarargs to this method in order to avoid a compiler warning “about potential heap pollution”. Adding this annotation to a method requires the method to be declared final, otherwise the compiler will reject the code.

Adding this final modifier then triggers java:S2333, which states that the final is redundant due to the class being declared final. This is the false positive, as the compiler requires the method to be final, even if the containing class is.

Hi @polyap, thank you for reporting this false positive and helping us to improve our rules.

I created [SONARJAVA-4525] - Jira to fix rule java:S2333, feel free to check its progress.

Cheers