简体   繁体   English

在Eclipse中快速实现包装(委托方法)?

[英]Fast implement wrapping (delegate methods) in Eclipse?

Is there some template or something to implement iterface methods with accessing to wrapped member? 是否有一些模板或东西来实现iterface方法访问包装成员?

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 现在我想通过将调用传递给包装来实现List<Something>

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

and so on. 等等。

There is. 有。 Use Source menu->Generate Delegate Methods... 使用源菜单 - >生成委托方法...

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, eg: 您创建了一个可选择实现接口的新类,并为其提供了一个具有您想要degate类型的字段,例如:

public class NewClass implements ThatInterface {
  private final ThatInterface delegate;

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

Then you apply the eclipse refactoring. 然后你应用eclipse重构。 (Cmd-3 deleg... is an easy way to access it.) Select the checkbox for the new field. (Cmd-3 deleg ...是一种访问它的简单方法。)选择新字段的复选框。 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.) (我认为,在Eclipse氧气的重构中存在一个错误,它会在接口上使用该关键字的方法复制default关键字。您可能需要删除该关键字。)

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... 等等...

Tested in Luna. 在Luna测试过。

Use shortcut Alt - Shift - S , M 2 times. 使用快捷键Alt - Shift - SM 2次。 Press Enter Enter键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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