Search code examples
javaintellij-idea

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;
    }
}

Solution

  • 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$);