2

Is there a way to apply new formatting rules for existing code in IntelliJ like how Eclipse does upon saving files?

For example in Eclipse, the "on save actions" can be configured with additional settings like:

  1. Insert final keyword wherever applicable (method arguments, object fields etc.)
  2. Wrap single line control statements with braces.
  3. Remove unused variables/private methods.

These would work for both new and existing code upon saving the file.

Although we can configure IntelliJ to follow these rules for new code, is there a way to apply these rules for existing code as well? Currently I just see basic re-formatting such as indentation, placement of braces and imports.

1 Answer 1

3

Make sure that all formating rules are set as desired in the standard IntelliJ rules.

Then open the Project Tool Window (View | Tool Windows | Project or Alt+1) and select a source package. You can then reformat all included source files at once (Code | Reformat Code or Ctrl+Alt+L).

To insert missing final in all your files, make sure that the inspection Field may be final (see settings) is activated. Select a non-final variable, press Alt+Enter and choose Make final | Run on... Choose Whole project as inspection scope. Another method is to Analyze | Inspect Code... and then run that inspection on your whole project.

BTW: I have switched from Eclipse to IntelliJ, too. In retrospect these additional "on save" rules only lead to extra-work when synchronizing with my team.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but apart from optimizing imports and re-arranging entries, it doesn't apply other rules (such as adding final to method parameters) which Eclipse does on saving.
true; this depends on the action; I have updated my answer for "insert missing final". "Remove unused..." can be done that way, too. The "wrap with braces" is covered by formatting rules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.