Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup IntelliJ IDEA 14 to add "final" keyword where possible?

Tags:

I would like to setup my IntelliJ IDEA 14 for automatic final keyword adding in all possible places (parameters, fields, etc.) to the existing Java class. I found some solutions with macros and shortcuts but I would like setup IntelliJ to add the final keyword when it saves the file. Does anyone know a good solution for this? Maybe can you recommend some plugin or combination of plugins?

like image 910
Piotr Pradzynski Avatar asked Apr 27 '15 09:04

Piotr Pradzynski


People also ask

How do I add final Auto in IntelliJ?

Go to preferences -> Code Style -> Code Generation and enable "Make generated local variables final" in the "Final modifier" section. You can also try searching for "final" in preferences. And, you can also export those settings and share them with your colleagues.

Where do I enter code in IntelliJ?

In the editor, press Ctrl+Shift+Enter or from the main menu select Code | Complete Current Statement. IntelliJ IDEA inserts the required trailing comma automatically in structs, slices, and other composite literals. The caret is moved to the position where you can start typing the next statement.

How do I enable preview feature in IntelliJ?

If you want to use preview features in the latest versions of Java in IntelliJ IDEA, you need to set the language level to "Preview". Go to Project Structure, ⌘; (macOS) or Ctrl+Alt+Shift+S (Windows/Linux), make sure you have the correct JDK selected, and pick the "Preview" option from the Language Level dropdown.


2 Answers

Open the "Configure inspections" view (click on the person in the hat icon). Search on "final" and you'll find various options in the code style section that you can enable to enable highlighting of candidates for final. You can then use alt-return to apply the suggestion within a given file.

I wouldn't recommend you do it automatically on saving!

like image 64
Steve Chaloner Avatar answered Sep 30 '22 00:09

Steve Chaloner


Preferences - Code style issues

Since the 2018.3 version we can enable the checkbox:

Preferences/Settings > Editor > Inspections > Java > Code style issues > Local variable or parameter can be final

Then perform the reformat code action.

If the Code cleanup checkbox is enabled then IDEA will automatically add final where possible.

screenshot of IntelliJ 2021.1 > Preferences/Settings > Editor > Inspections > Java > Code style issues > Local variable or parameter can be final

like image 45
Egor Klepikov Avatar answered Sep 29 '22 22:09

Egor Klepikov