java:S2694 false-positive on local classes

  • What language is this for? Java
  • Which rule? java:S2694 “Inner classes which do not reference their owning classes should be static
  • SonarLint 9.1.0.81411 under Eclipse 4.30 (2023-12)

Method- and constructor-local classes cannot be static (see JLS §14.3), but the rule reports that those classes should be marked as such if they don’t reference external variables or fields.

Sample code:

public class Foo {
	public Foo() {
		class Bar { }
	}
	
	public void method() {
		class Baz { }
	}
}

Both Bar and Baz are wrongly flagged as non-compliant.

Hello @ivaniesta14,

Thanks for the message, Looks like the implementation of the rule doesn’t take into account local classes. Here is the ticket to fix it:

https://sonarsource.atlassian.net/browse/SONARJAVA-4829

Best,
Margarita

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

Hello @ivaniesta14, after having a closer look at the implementation I found it correct. The raised message says: Make this local class a “static” inner class., thus the fix in your example is:

public class Foo {
  public Foo() { }
  public void method() { }

  private static class Bar { } // Compliant
  private static class Baz { } // Compliant
}

I will improve the description and the message reported to avoid confusion.

Cheers,
Angelo