Explain Codes LogoExplain Codes Logo

Intellij: Never use wildcard imports

java
best-practices
tools
performance
Anton ShumikhinbyAnton Shumikhin·Nov 9, 2024
TLDR

Never want to see wildcard imports in your IntelliJ? Follow these steps: Navigate to Editor > Code Style > Java > Imports and tweak the Class count to use import with '*' to 999. What's that? You'll need to import a thousand classes from the same package for the wildcard to show up? Yep, that's the idea!

// If you have more than 999 classes, you might be inventing your own language! Class count to use import with '*': 999 Names count to use static import with '*': 999

Once you've taken care of that, you're home free. IntelliJ will favor listing all your imports explicitly, your code will thank you, and you can rest easy knowing you've taken another step in the right direction for maintaining a clean codebase.

How to enable single class imports in IntelliJ IDEA

Access the Preferences (⌘ + , on macOS / Ctrl + Alt + S on Windows/Linux) and make sure the "Use single class import" option is ticked. It's like flicking a switch - your code just got a cleaner look!

// Keep it classy with single class import Use single class import: [x]

IntelliJ versions and import settings

Compatibility? Check. These settings are consistent across IntelliJ IDEA versions, from the revered ancestors at 13.x to the new, flashy 2021 versions.

Kotlin and wildcard imports: special notes

For the Kotlin developers in the house, remember to exclude the java.util.* wildcard import in your settings.

// For Kotlin imports, let's keep it specific Packages to Use Import with '*': (Ensure this list is empty)

Unmanageable imports and IDE performance

During your editing spree in IntelliJ settings, sniff out the unused entries in the "Packages to use import with '*'". Remove them and you'll boost your IDE's performance alongside tidying up your code.

Manual replacement of wildcard imports

Spot a wildcard import sneaking around in your code? Send it packing with the Replace in Path feature (Ctrl+Shift+R on Windows/Linux or ⌘+Shift+R on macOS), and this handy regular expression:

// Who doesn't love a good old-fashioned game of hide and seek with imports import\s+([\w\.]+)\.\*;

Prioritizing readability

Wildcard imports? More like wild imports! You may think they're convenient, but they're really parties you don't want to be invited to. Aim for clarity and assurance with explicit imports.

Enforcing import style with linters and checkstyle

Round off your clean coding adventure with some linter rules or checkstyle configurations. Watch wildcard imports drop into oblivion, while your team adopts a more uniform and maintainable approach to importing classes.