In all my java files of my project, I want to replace occurrences of this:
myObject.getName() == null
With that:
myObject.hasName()
Is there any action or strategy to do this with IntelliJ IDEA?
getName
method of my class MyClass
and not to replace code, that refers to methods called getName
of other classes.myObj
or objX
) it should also work. Calls like getObject().getName()
should also be found. (The search has to care about semantics).To extract method: Select a code fragment you want to extract to a method. Press Ctrl+Alt+M or from the main menu, select Refactor | Extract | Method. In the dialog that opens, configure a method options, such as visibility, parameters, and so on. You can also change a name of the method if you need.
Highlight the code you want to extract to a method and press ⌥⌘M (macOS), or Ctrl+Alt+M (Windows/Linux), to extract it.
Extract method Last modified: 27 September 2022. The Extract Method refactoring lets you take a code fragment that can be grouped, move it into a separated method, and replace the old code with a call to the method.
Use Find and Replace Code Duplicates.
Create the instance method:
public boolean hasName() {
return getName() == null;
}
myObject.getName() == null
, then using actions Refactor | Extract | Method... and Refactor | Move..., so you don't have to type any code.Click on the method and use Refactor | Find and Replace Code Duplicates.
However it will not refactor usages like these:
String name = myObject.getName();
if (name == null) {
...
}
You can also use this action on a non-instance method:
private boolean hasName(MyClass myObject) {
return myObject.getName() == null;
}
which will result in making the method static, then use Refactor | Convert To Instance Method. Same result.
Use Structural Search & Replace (Edit | Find | Replace Structurally...), it is designed for use cases like this.
Use Search template:
$x$.getName() == null
Replacement template:
$x$.hasName()
Click the Edit Variables... button and specify Expression type (regexp) as MyClass
. When searching this will also find your example of getObject().getName() == null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With