Avoid Wildcard (Star) Imports
ID |
java.avoid_star_import |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
code-style, imports |
Description
Reports import declarations that use the wildcard form (import java.util.*). Wildcard imports hide which types are actually used, making the code harder to understand and review.
A star import is accepted when it collapses at least maxExplicitImports distinct types from that package — the point at which the explicit list costs more than it explains. Annotation uses count towards that total: import lombok.* standing in for six annotations is exactly the case the threshold exists to accept.
Static star imports (import static com.example.Foo.*) are not reported by default. Counting what one collapses would need every simple-name use resolved to the starred class’s static members, which this rule does not attempt, so reporting them at all would mean reporting every one regardless of how much it saves. Set reportStaticImports to true to flag them anyway.
Rationale
When a wildcard import brings in an entire package, readers must consult external documentation to determine which types are referenced. Wildcard imports also increase the risk of accidental name collisions: if two wildcard-imported packages both define a class with the same simple name, the code fails to compile or silently resolves to the wrong type after a dependency upgrade.
// Bad — hides which types are used
import java.util.*;
import java.io.*;
import static org.junit.Assert.*;
Remediation
Replace wildcard imports with explicit, single-type imports.
// Good — explicit imports
import java.util.List;
import java.util.Map;
import java.io.File;
import static org.junit.Assert.assertEquals;