
org.sonar.l10n.java.rules.java.S2208.html Maven / Gradle / Ivy
Why is this an issue?
Using wildcards in imports may look cleaner as it reduces the number of lines in the import section and simplifies the code.
On the other hand,
it makes the code harder to maintain:
- It reduces code readability as developers will have a hard time knowing where names come from.
- It could lead to conflicts between names defined locally and the ones imported.
- It could later raise conflicts on dependency upgrade or Java version migration, as a wildcard import that works today might be broken tomorrow.
That is why it is better to import only the specific classes or modules you need.
Exceptions
Static imports are ignored by this rule. For example:
import static java.lang.Math.*;
will not raise an issue;
How to fix it
Depending on your IDE you can solve this issue almost automatically:
Look for Organize/Optimize imports
actions. These actions can also often be applied automatically on save.
Note: To make this work properly, you must adjust IDE settings to
use a very high allowed class count usage
before using wildcards.
Resolving this issue manually will require a step-by-step approach:
- Remove one wildcard import and note down compilation failures.
- For each missing class, import it back with the package prefix.
- When the code compiles again, proceed with the next wildcard import.
Code examples
Noncompliant code example
import java.sql.*; // Noncompliant
import java.util.*; // Noncompliant
private Date date; // Date class exists in java.sql and java.util. Which one is this?
Compliant solution
import java.sql.Date;
import java.util.List;
import java.util.ArrayList;
private Date date;
© 2015 - 2025 Weber Informatics LLC | Privacy Policy