Fabio A.
Fabio A.

Reputation: 2724

Is there a way to automate repetitive refactoring operations in Intellij-IDEA?

In order to implement a feature in a project I'm working on, I've had to throw a checked exception from a method which is used, in cascade, by hundreds of other methods throughout tens of other classes in the whole project. Consequently, I have got to do some heavy refactoring which Intellij assists me in doing with pop-ups like this one:

Example of refactoring popup

Now, while this intellij feature is very helpful, having to go through the whole codebase is still taking a (to me) unbearable amount of time. The task is actually very repetitive:

  1. Go through all the "unreported exception XX; must be caught or declared to be thrown" errors.
  2. Make the pop up emerge.
  3. If the two options shown in the picture are both present, then choose the first one.
  4. If only "Surround with try/catch" is present, use that one and substitute the e.printStackTrace() call that gets automatically emitted with code of my own.
  5. Repeat from point 1 until no more errors are reported.

So, the question is: is there any way to automate this process in IntelliJ?

Upvotes: 3

Views: 1332

Answers (2)

Balazs Kelemen
Balazs Kelemen

Reputation: 91

In a general point of view IntellJ IDEA has a batch refactoring feature which can be accessed as follows:

  1. Locate one occurrence of the problem.
  2. Over the problematic part, access the Intentions popup, find the resolution and in the submenu you will find a "Run inspection on..." function.
  3. Here you define the scope of the search, e.g. all files in the project.
  4. After finding all occurrences select an Inspection entry on the tree (or any other selection can be made, e.g. select all).
  5. If the "Apply a quick fix" (light bulb) tool enabled you have the possibility to fix all the problems with one click now.

I believe it depends on the inspection and the resolutions available for that.

Upvotes: 1

matt helliwell
matt helliwell

Reputation: 2678

The only automated way I've found for this is to use the refactoring. On the method that is to throw an exception, choose refactor->change signature. Add in the exception to the signature. Choose the option to propagate the exception and then choose refactor.

It should then add throws clauses to all the methods which call the function.

This works fine for a small number of methods. I haven't tried it with hundred of methods.

Unfortunately I couldn't get the code analysis, which has a "fix all" option, to report this error. If it did report the error then that would've been a simpler way of fixing all the problems.

Upvotes: 2

Related Questions