简体   繁体   中英

Intellij - refactor getters and setters using delegate class

Here's what I'd like to do. Let's say I have this code:

public class Foo {

  private Bar bar = new Bar();

  public void doWork() {
    bar.setA(5);
    bar.setB(10);
  }
}

public class Bar {
  private int a;
  private int b;

  public void setA(int a) { this.a = a; }
  public void setB(int b) { this.b = b; }

  ...
}

I want to extract members a and b from Bar into a separate Container class and end up with this code. Notice that Foo doesn't call setA on bar anymore, instead it requests container and calls a setter on it instead:

public class Foo {

  private Bar bar = new Bar();

  public void doWork() {
    bar.getContainer.setA(5);
    bar.getContainer.setB(10);
  }
}


public class Bar {
  private Container container;

  public Container getContainer() { return container; }

  ...
}

public class Container {
  private int a;
  private int b;

  public void setA(int a) { this.a = a; }
  public void setB(int b) { this.b = b; }

  ...
}

Is there a way to do this in IntelliJ?

I could try using Refactor -> Extract -> Delegate, but in that case IntelliJ leaves setA and setB methods in Bar and doesn't change code in Foo:

public class Bar {
  private Container container;

  public void setA(int a) { container.setA(a); }
  public void setB(int b) { container.setB(b); }

  ...
}

which is not quite what I want.

Select the piece of code inside class bar...

private int a;
private int b;

public void setA(int a) { this.a = a; }
public void setB(int b) { this.b = b; }

On the main menu, or from the context menu of the selection, choose Refactor | Extract | Method Object . You will also have option to choose to create inner class, or anonymous class. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM