Skip to content
Merged
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"ruleKey": "S8445",
"hasTruePositives": true,
"falseNegatives": 0,
"falsePositives": 0
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,14 @@
import java.lang.reflect.Constructor;
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.sonar.plugins.java.api.semantic.Symbol;
import org.sonar.plugins.java.api.tree.CompilationUnitTree;
import org.sonar.plugins.java.api.tree.ExpressionStatementTree;
import org.sonar.plugins.java.api.tree.ExpressionTree;
import org.sonar.plugins.java.api.tree.IdentifierTree;
import org.sonar.plugins.java.api.tree.ImportTree;
import org.sonar.plugins.java.api.tree.MethodInvocationTree;
import org.sonar.plugins.java.api.tree.MethodTree;

Expand All @@ -40,6 +44,33 @@ void private_constructor() throws Exception {
constructor.newInstance();
}

@Test
void concatenate_null() {
assertThat(ExpressionsHelper.concatenate(null)).isEmpty();
}

@ParameterizedTest
@CsvSource({
"import A;, A",
"import java.util.List;, java.util.List",
"import java.util.regex.Pattern;, java.util.regex.Pattern",
"import java.util.*;, java.util.*",
"import static java.util.Collections.emptyList;, java.util.Collections.emptyList",
"import static java.util.Collections.*;, java.util.Collections.*",
"import module java.base;, java.base"
})
void concatenate(String importStatement, String expected) {
String code = importStatement + "\nclass C {}";
ExpressionTree qualifiedId = getImportQualifiedIdentifier(code, 0);
assertThat(ExpressionsHelper.concatenate(qualifiedId)).isEqualTo(expected);
}

private ExpressionTree getImportQualifiedIdentifier(String code, int importIndex) {
CompilationUnitTree compilationUnit = parse(code);
ImportTree importTree = (ImportTree) compilationUnit.imports().get(importIndex);
return (ExpressionTree) importTree.qualifiedIdentifier();
}

@Test
void simpleAssignment() {
String code = newCode( "int foo() {",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package checks;

// Basic violation: package import after single-type import
import java.util.List; // Compliant
import java.io.*; // Noncompliant {{Reorder this on-demand package import to come before single-type imports.}}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just noticed this. Right now the squiggly line is on the import keyword. It think it it would be nicer to underline the import itself. It can be done with reportIssue(importTree.qualifiedIdentifier(), message); and tested with
// ^^^^^^^^^ on the next line.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll do it, but as we've discussed, the whole functionality will be updated to QuickFix and single raise. So there's no real sense doing it.

// ^^^^^^^^^
import java.util.Map; // Compliant

// Static import violations
import static java.lang.Math.PI; // Compliant
import static java.util.Collections.*; // Noncompliant {{Reorder this static on-demand package import to come before static single-type imports.}}
// ^^^^^^^^^^^^^^^^^^^^^^^
// Module import violation - comes after static imports
import module java.base; // Noncompliant {{Reorder this module import to come before static on-demand package imports.}}

// These are compliant since they come after module import (which resets the ordering)
import java.sql.*; // Compliant
import java.time.Instant; // Compliant
import static java.lang.System.out; // Compliant

class ImportDeclarationOrderCheckSample {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package checks;

// All imports in correct order - no violations expected

// Module imports
import module java.base;

// Package imports (on-demand)
import java.io.*;
import java.sql.*;

// Single-type imports
import java.util.List;
import java.util.Map;
import java.time.Instant;

// Static package imports (on-demand)
import static java.util.Collections.*;

// Static single-type imports
import static java.lang.Math.PI;
import static java.lang.System.out;


class ImportDeclarationOrderCheckSampleNoIssuesSample {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* SonarQube Java
* Copyright (C) 2012-2025 SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.JavaVersion;
import org.sonar.plugins.java.api.JavaVersionAwareVisitor;
import org.sonar.plugins.java.api.tree.CompilationUnitTree;
import org.sonar.plugins.java.api.tree.ImportTree;
import org.sonar.plugins.java.api.tree.Tree;

@Rule(key = "S8445")
public class ImportDeclarationOrderCheck extends IssuableSubscriptionVisitor implements JavaVersionAwareVisitor {

@Override
public boolean isCompatibleWithJavaVersion(JavaVersion version) {
return version.isJava25Compatible();
}

@Override
public List<Tree.Kind> nodesToVisit() {
return Collections.singletonList(Tree.Kind.COMPILATION_UNIT);
}

@Override
public void visitNode(Tree tree) {
CompilationUnitTree compilationUnit = (CompilationUnitTree) tree;

List<ImportTree> imports = new ArrayList<>();
// Collect all import statements
compilationUnit.imports()
.stream()
.filter(importTree -> importTree.is(Tree.Kind.IMPORT))
.map(ImportTree.class::cast)
.forEach(imports::add);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

using List<ImportTree> imports = (...).toList() creates unmodifiable list, which is generally preferred.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's really preferred when it's publicly accessible / can be potentially modified by external modules. In the case when it's private access within one class, I don't think it's important.


analyzeImportOrder(imports);
}

private void analyzeImportOrder(List<ImportTree> imports) {
if (imports.size() <= 1) {
return;
}

ImportType previousType = ImportType.SENTINEL_IMPORT;
for (ImportTree importTree : imports) {
ImportType currentType = classifyImport(importTree);

if (currentType.ordinal() < previousType.ordinal()) {
String message = buildMessage(currentType, previousType);
reportIssue(importTree.qualifiedIdentifier(), message);
}

previousType = currentType;
}
}

private static String buildMessage(ImportType currentType, ImportType previousType) {
return String.format("Reorder this %s import to come before %s imports.",
currentType.getDescription(),
previousType.getDescription());
}

private static ImportType classifyImport(ImportTree importTree) {
boolean isWildcard = isWildcardImport(importTree);

if (importTree.isModule()) {
return ImportType.MODULE_IMPORT;
}

if (importTree.isStatic()) {
return isWildcard ? ImportType.STATIC_PACKAGE_IMPORT : ImportType.STATIC_SINGLE_TYPE_IMPORT;
}

return isWildcard ? ImportType.PACKAGE_IMPORT : ImportType.SINGLE_TYPE_IMPORT;
}

private static boolean isWildcardImport(ImportTree importTree) {
return "*".equals(importTree.qualifiedIdentifier().lastToken().text());
}

enum ImportType {
SENTINEL_IMPORT("sentinel"),
MODULE_IMPORT("module"),
PACKAGE_IMPORT("on-demand package"),
SINGLE_TYPE_IMPORT("single-type"),
STATIC_PACKAGE_IMPORT("static on-demand package"),
STATIC_SINGLE_TYPE_IMPORT("static single-type");

private final String description;

ImportType(String description) {
this.description = description;
}

public String getDescription() {
return description;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
package org.sonar.java.checks;

import org.sonar.check.Rule;
import org.sonar.java.checks.helpers.ExpressionsHelper;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.tree.IdentifierTree;
import org.sonar.plugins.java.api.tree.ExpressionTree;
import org.sonar.plugins.java.api.tree.ImportTree;
import org.sonar.plugins.java.api.tree.MemberSelectExpressionTree;
import org.sonar.plugins.java.api.tree.Tree;
import org.sonar.plugins.java.api.tree.Tree.Kind;

Expand All @@ -40,18 +40,9 @@ public void visitNode(Tree tree) {
ImportTree importTree = (ImportTree) tree;

// See RSPEC-2208 : exception with static imports.
if (fullQualifiedName(importTree.qualifiedIdentifier()).endsWith(".*") && !importTree.isStatic()) {
String qualifiedName = ExpressionsHelper.concatenate((ExpressionTree) importTree.qualifiedIdentifier());
if (qualifiedName.endsWith(".*") && !importTree.isStatic()) {
reportIssue(importTree.qualifiedIdentifier(), "Explicitly import the specific classes needed.");
}
}

private static String fullQualifiedName(Tree tree) {
if (tree.is(Tree.Kind.IDENTIFIER)) {
return ((IdentifierTree) tree).name();
} else if (tree.is(Tree.Kind.MEMBER_SELECT)) {
MemberSelectExpressionTree m = (MemberSelectExpressionTree) tree;
return fullQualifiedName(m.expression()) + "." + m.identifier().name();
}
throw new UnsupportedOperationException(String.format("Kind/Class '%s' not supported", tree.getClass()));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* SonarQube Java
* Copyright (C) 2012-2025 SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.checks;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.sonar.java.checks.verifier.CheckVerifier;

import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath;

class ImportDeclarationOrderCheckTest {

@Test
void basic_import_ordering() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/ImportDeclarationOrderCheckSample.java"))
.withCheck(new ImportDeclarationOrderCheck())
.withJavaVersion(25)
.verifyIssues();
}

@Test
void no_issue_on_java_24() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/ImportDeclarationOrderCheckSample.java"))
.withCheck(new ImportDeclarationOrderCheck())
.withJavaVersion(24)
.verifyNoIssues();
}

@Test
@DisplayName("The same imports but correctly ordered")
void correctly_ordered_imports() {
CheckVerifier.newVerifier()
.onFile(mainCodeSourcesPath("checks/ImportDeclarationOrderCheckSampleNoIssuesSample.java"))
.withCheck(new ImportDeclarationOrderCheck())
.withJavaVersion(25)
.verifyNoIssues();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<p>This rule raises an issue when import declarations are not organized into distinct groups based on their kind and specificity level.</p>
<h2>Why is this an issue?</h2>
<p>Import declarations should be organized into distinct groups based on their kind to improve readability and make shadowing behavior explicit. The
grouping order should reflect specificity levels: module imports first (least specific), followed by on-demand package imports (intermediate
specificity), single-type imports (most specific), then static on-demand imports, and finally single-static imports.</p>
<p>When imports are mixed or ordered arbitrarily, it becomes harder to understand which declarations might shadow others. Java’s import shadowing
rules mean that more specific imports can override less specific ones, so organizing imports by specificity makes these relationships clearer and
improves code maintainability by providing a consistent, predictable structure.</p>
<h2>How to fix it</h2>
<p>Organize import declarations into the following groups, in this order:</p>
<ol>
<li> Module imports (e.g., <code>import module java.base;</code>) </li>
<li> On-demand package imports (e.g., <code>import javax.swing.text.*;</code>) </li>
<li> Single-type imports (e.g., <code>import java.util.List;</code>) </li>
<li> Static on-demand imports (e.g., <code>import static java.util.Collections.*;</code>) </li>
<li> Single-static imports (e.g., <code>import static java.util.regex.Pattern.compile;</code>) </li>
</ol>
<p>Separate each group with a blank line for better visual organization.</p>
<h3>Code examples</h3>
<h4>Noncompliant code example</h4>
<pre data-diff-id="1" data-diff-type="noncompliant">
import java.sql.Date;
import module java.base;
import static java.util.Collections.*;
import javax.swing.text.*;
import module java.desktop;
import static java.util.regex.Pattern.compile;
import java.util.List;

class Foo {
// ...
}
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="1" data-diff-type="compliant">
// Module imports
import module java.base;
import module java.desktop;

// On-demand package imports
import javax.swing.text.*; // resolves the ambiguity of the simple name Element

// Single-type imports
import java.sql.Date; // resolves the ambiguity of the simple name Date
import java.util.List;

// Static on-demand imports
import static java.util.Collections.*;

// Single-static imports
import static java.util.regex.Pattern.compile;

class Foo {
// ...
}
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
<li> <a href="https://docs.oracle.com/javase/specs/jls/se25/html/jls-7.html#jls-7.5">Java Language Specification - Import Declarations</a> </li>
<li> <a href="https://openjdk.org/jeps/511">JEP 511: Module Import Declarations</a> </li>
</ul>

Loading
Loading