Meo
Meo

Reputation: 12491

Refactor method/constructor parameters to insert the whole object in IntelliJ

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

Answers (3)

JinoBetti
JinoBetti

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

Andy Turner
Andy Turner

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

danijax
danijax

Reputation: 69

  1. Go to the Bar class definition then right-click and select refactor.
  2. Select Change Signature
  3. Remove the old parameters(-)
  4. Add the new Parameter using the fully qualified name(+)

Upvotes: -1

Related Questions