Massively refactor - how to add final keyword to Java method argument
Solution 1
You can use IntelliJ's inspections mechanism for this:
- Navigate to Analyze->Run Inspection by Name
- Search for the "Local variable or parameter can be final" warning
- Make sure that "Report method parameters" is the only option checked.
- Select the root of the tree (it should read Local variable or parameter can be final"
- 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:
- Navigate to File->Settings->Editor->Inspections
- Search for the "Local variable or parameter can be final" warning
- 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.
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.
Related videos on Youtube
Comments
-
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 over 6 yearsDo you know, if there is a similar way to add the final attribute to class fields?
-
Mureinik over 6 years@cwoebker You could use the same approach with the "Field may be final" inspection.
-
Tomas Bjerre over 5 yearsOr let Eclipse "save actions" add final everywhere possible.
-
krems over 5 yearsYou 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 over 3 yearsThis is good but it doesn’t know that Lombok
val
is final. But thanks! -
m2sj about 2 years@Mureinik Your answer was so helpful to me. thank you.