Intellij IDEA fetch constant through whole project

Let's say I have a "magic string" in four classes, and I want it to be replaced in all places with one constant from some constant class. (I'm talking about Java / Groovy classes, but any other languages ​​would be helpful too.) The best solution I can think of is to extract the constant into one class and then use the Replace in Path dialog for the rest. But that doesn't solve the import of the constant class, which is quite a lot of work. Is there a better way?

I found this documentation page but there is no functionality about this.

+3


source to share


2 answers


Your best bet is to find and replace duplicate code ... refactoring.



Extract the constant as usual, then call Find and replace the duplicate code ... with the entered constant. It can find all the places in your project where it is used "magic string"

and suggests replacing it with a constant reference.

+2


source


It's actually not that hard to do with normal action Replace in Path

.

First, you need to go in Settings

and enable this: Editor

β†’ General

β†’ Auto Import

β†’ Add unambiguous imports on the fly

Now create a constant in some class and do Replace in Path

(ctrl-shift-R)

Search text: "foo"



Replaced by: Constants.FOO

Now, use Find and keep using Replace to change this magic value in all files except the class Constants

where it is defined.

You should notice that imports are automatically added to every file (assuming the constant is unique).

+1


source







All Articles