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

John Zhang picture John Zhang · Feb 20, 2017 · Viewed 8.7k times · Source

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?

Answer

Mureinik picture Mureinik · Feb 20, 2017

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.