Massively refactor - how to add final keyword to Java method argument

10,446

Solution 1

You can use IntelliJ's inspections mechanism for this:

  1. Navigate to Analyze->Run Inspection by Name
  2. Search for the "Local variable or parameter can be final" warning
  3. Make sure that "Report method parameters" is the only option checked.
  4. Select the root of the tree (it should read Local variable or parameter can be final"
  5. Click ALT+ENTER and select "make final". This should add the final modifier in all the missing places.

Once you've done this, you may want to enable this inspection in your IDE so it warns you about making further mistakes:

  1. Navigate to File->Settings->Editor->Inspections
  2. Search for the "Local variable or parameter can be final" warning
  3. Make sure that "Report method parameters" is the only option checked.

Solution 2

In IntelliJ you can check the "Make generated local variables final" and "Make generated parameters final" options enabled.

In IntelliJ 2017.3 it's in Preferences -> Editor -> Code Style -> Java -> Code Generation tab.

enter image description here

Solution 3

Disclaimer: I don't want to start an IDE war and I don't use intelliJ, so there might be a way to do it there. But since you asked about a tool to do that and the manual effort could justify using a different IDE for it, here you go in eclipse.

In eclipse you can configure the "clean up" task to add final wherever possible. The clean up task can be run on single editor windows and also on the whole project from the "source" context menu.

Share:
10,446

Related videos on Youtube

John Zhang
Author by

John Zhang

A passionate programmer and skier!

Updated on June 05, 2022

Comments

  • John Zhang
    John Zhang almost 2 years

    This might be a simple question: How can I massively refactor my Java code to make most of the method argument as "final"? This is to follow one of our "checkstyle" rule. We have thousands of Java files, so manually edit all of them seems not an acceptable solution to us.

    I didn't find any such refactor option in IntelliJ. Anybody knows any tool that can help? Or any smart approach to achieve that?

  • cwoebker
    cwoebker over 6 years
    Do you know, if there is a similar way to add the final attribute to class fields?
  • Mureinik
    Mureinik over 6 years
    @cwoebker You could use the same approach with the "Field may be final" inspection.
  • Tomas Bjerre
    Tomas Bjerre over 5 years
    Or let Eclipse "save actions" add final everywhere possible.
  • krems
    krems over 5 years
    You can also tick CleanUp in commit dialog and inspections will be processed (if autofix available, which is the case here) Thus you won't need to do this massive refactoring again in future
  • mirabilos
    mirabilos over 3 years
    This is good but it doesn’t know that Lombok val is final. But thanks!
  • m2sj
    m2sj about 2 years
    @Mureinik Your answer was so helpful to me. thank you.