Reputation: 12491
I want to refactor the code so that the whole object input
is passed as a parameter instead of its parts input.getI(), input.getJ()
.
I could easily do the opposite with Extract Parameter
action, but how do I refactor it like this across the code base, in IntelliJ?
public static void main(String[] args) {
Foo input = new Foo(0, 1);
//What I have:
new Bar(input.getI(), input.getJ());
print(input.getI(), input.getJ());
//What I want:
//new Bar(input);
//print(input);
}
public static void print(int i, int j) {
System.out.println(i + j);
}
public static class Foo {
private int i;
private int j;
public Foo(int i, int j) {
this.i = i;
this.j = j;
}
public int getI() {
return i;
}
public int getJ() {
return j;
}
}
public static class Bar {
private int i;
private int j;
public Bar(int i, int j) {
this.i = i;
this.j = j;
}
}
Upvotes: 4
Views: 1330
Reputation: 21
First extract a method with Ctrl+Alt+M with just the call to print(input.getI(), input.getJ());
IntelliJ will extract the method with the whole object as print(Foo foo)
Then inline the old public static void print(int i, int j)
method with Ctrl+Alt+N
Upvotes: 2
Reputation: 140309
First, add overloads for the method/constructor you want:
public static void print(Foo foo) { ... }
public Bar(Foo foo) { ... }
Then use structural search and replace (Edit > Find > Replace Structurally) to replace:
print($f$.getI(), $f$.getJ());
with
print($f$);
(If necessary, constrain $f$
to be of type Foo
by clicking "Edit Variables", pick f
from the list, and set "Expected Type (regexp)" to "Foo")
Similarly, replace:
new Bar($f$.getI(), $f$.getJ());
with
new Bar($f$);
Upvotes: 4
Reputation: 69
Bar
class definition then right-click and select
refactor. Upvotes: -1