Tips & Tricks

Structural search and replace

Searching through a large project is always tiresome. Changing a large project is usually more tiresome even with all cool IDE features such as search by regular expressions, find usages, or automated refactoring.
For example, you may need to find all the classes that implement exactly two interfaces or find all methods that accept a parameter with a specific name and/or type. Finding usages or simple search may produce too long lists of results, especially if your project is really large.
The solution suggested by IntelliJ IDEA is Structural Search and Replace (SSR) where you can define the code pattern to narrow the search scope.
Let’s consider an example when you need to find all inner classes in your project. The search template will look as follows:

class $Class${
class $InnerClass${}
}

Here $Class$ and $InnerClass$ can be any class names.
If you need to find an inner class that implements, let’s say, Runnable interface you can write the following:

class $Class$ {
class $InnerClass$ implements Runnable{}
}

To find all the inner classes that implement any interface, it is enough to write this:

class $Class$ {
class $InnerClass$ implements $Interface${}
}

If “any interface” is not what you need, it is possible to apply powerful constraints to the variable.
Of course, you can also use the templates for replacing the found code. For example, you may wish to convert all the found classes to become final. The screenshot shows how it looks in IntelliJ IDEA user interface.
Screenshot/
Once created, a template can be saved and then reused. And of course, IntelliJ IDEA provides a lot of predefined templates.
Get interested? Learn more about SSR in Structural Search and Replace: What, Why, and How-to written by Maxim Mossienko, one of the JetBrains developers and originator of the Structural Search and Replace feature.

Note   This tip was originally posted at www.javalobby.org.

Technorati tags: Java, refactoring
image description

Discover more