LoginSignup
3

More than 3 years have passed since last update.

IntelliJ IDEA で Java の import 宣言を最適化する (Optimize imports)

Last updated at Posted at 2019-08-09

Optimize Imports の実行

IntelliJ IDEA のメニューから Code → Optimize Imports を選択する。

Optimize Imports 実施前:
intellij1.png

Optimize Imports 実施後:
intellij2.png

(IntelliJ IDEA 2018.3.3 (Community Edition) で確認)

最適化の内容

Optimize Imports を実行することで以下のような最適化が行われる。

  • 使用していないクラスの import 文を削除
  • import 宣言の順番を適切に並び替える
  • アスタリスク「*」によるオンデマンド型インポート宣言 (type-import-on-demand declaration) をクラス毎の個別のインポート (single-type-import declaration) に展開

Auto import - Help | IntelliJ IDEA

The Optimize Imports feature helps you remove unused imports, add missing imports, and organize import statements in the current file or in all files in a directory at once.

Optimize Imports のショートカットキー

Optimize Imports はショートカットキーでも実行可能。
macOS では control + command + O
Linux と Windows では Ctrl + Alt + O

IntelliJ IDEA DEFAULT KEYMAP

Type-Import-on-Demand Declarations の設定

Type-Import-on-Demand Declarations (オンデマンドタイプのインポート宣言) は、アスタリスク「*」を使ってパッケージに属するクラスをすべてインポートする Java の文法。

Optimize Import 機能を使うと、同じパッケージの import 文の数が多いとアスタリスク「*」でまとめられてしまうことがある。

intellij3.png

これは、設定 Preferences → Editor → Code Style → Java → Imports の 「Class count to use import with '*'」 にて、アスタリスク「*」でまとめる import 文の下限数を設定することができる。

intellij4.png

(IntelliJ IDEA 2018.3.3 (Community Edition) で確認)

自動で Optimize imports を実行する

設定 Preferences → Editor → General → Auto Import の 「Optimize imports on the fly (for current project)」 にチェックを入れることで、ソースコードを修正した際に自動で Optimize imports が実行される。

スクリーンショット 2019-11-20 5.51.20.png

(IntelliJ IDEA 2019.2.4 (Community Edition) で確認)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3