Fast implement wrapping (delegate methods) in Eclipse?
Asked Answered
S

3

22

Is there some template or something to implement iterface methods with accessing to wrapped member?

For example, suppose I have

public class MyClass implements List<Something> {

    private final List<Something> core;

...
}

and now I want to implement List<Something> by passing calls to wrapped like

@Override
public int size() {
    return core.size();
}

and so on.

Smith answered 13/3, 2013 at 21:45 Comment(0)
S
29

There is. Use Source menu->Generate Delegate Methods...

Sunshinesunspot answered 13/3, 2013 at 21:48 Comment(0)
D
9

I'll say a bit more about how the "Generate Delegate Methods" refactoring works to create a forwarding class like you describe.

You make a new class which optionally implements the interface, and provide it with a field with the type you want to delgate, e.g.:

public class NewClass implements ThatInterface {
  private final ThatInterface delegate;

  public MyClass(ThatInterface delegate) {
    this.delegate = delegate();
  }
}

Then you apply the eclipse refactoring. (Cmd-3 deleg... is an easy way to access it.) Select the checkbox for the new field. All of its methods will be added as delegates.

(There is a bug, I think, in the refactoring for Eclipse oxygen, where it will copy the default keyword from methods with that keyword on the interface. You may need to delete that keyword.)

So for a delegate to a List the refactoring produced:

public class NewClass {
   private final List<String> delegate;

   public NewClass(List<String> delegate) {
       this.delegate = delegate;
   }


   public void forEach(Consumer<? super String> action) {
       delegate.forEach(action);
   }
   public int size() {
       return delegate.size();
   }
   public boolean isEmpty() {
       return delegate.isEmpty();
   }
   public boolean contains(Object o) {
       return delegate.contains(o);
   }

and so on...

Dichlamydeous answered 9/4, 2018 at 22:22 Comment(0)
D
2

Tested in Luna.

Use shortcut Alt-Shift-S, M 2 times. Press Enter

Drysalt answered 15/4, 2016 at 6:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.