Java使用其他类型参数扩展参数化接口

时间:2018-05-04 10:15:41

标签: java generics type-erasure

将我的帖子脚本移到顶部,这样如果我将这个帖子发布到错误的网站,人们就不会浪费时间:我无法决定这是属于这里还是{ {3}}。如果后者被认为更合适,我很高兴看到它移动。

我有一个参数化接口,其方法采用Consumer,如果某个条件成立,则以this作为参数调用它。否则它返回this(使其在呼叫站点上可链接,因为您可能已经收集了):

public interface SomeInterface<T> {

  boolean someCondition();

  default SomeInterface<T> someMethod(
      Consumer<SomeInterface<? extends T>> action) {
    if (someCondition()) {
      action.accept(this);
    }
    return this;
}

现在我想通过添加另一个参数来扩展此功能,以便我可以向调用者返回其他信息:

public interface SomeInterfaceExtended<T, U> extends SomeInterface<T> {

  U getAdditionalInformation();

  @Override
  SomeInterfaceExtended<T, U> someMethod(
      Consumer<SomeInterfaceExtended<? extends T, U>> action) {
    if (someCondition()) {
      action.accept(this);
    }
    return this;
  }
}

这当然不起作用,因为这两种方法具有相同的擦除功能。我最终没有扩展界面,而是定义了所有相同的方法并且使用&#34;扩展&#34;接口的实现者委托给&#34; basic&#34;的实例。接口:

public interface SomeInterface<T> {

  boolean someCondition();

  default SomeInterface<T> someMethod(
      Consumer<SomeInterface<? extends T>> action) {
    if (someCondition()) {
      action.accept(this);
    }
    return this;
}
...
public interface SomeInterfaceExtended<T, U> {

  U getAdditionalInformation();

  boolean someCondition();

  default SomeInterfaceExtended<T, U> someMethod(
      Consumer<SomeInterfaceExtended<? extends T, U>> action) {
    if (someCondition()) {
      action.accept(this);
    }
    return this;
  }    
}
...
public class SomeClass<T> implements SomeInterface<T> {
  @Override
  public boolean someCondition() {
    // whatever
  }
}
...
public class SomeClassExtended<T, U> implements SomeInterfaceExtended<T, U> {

  private final SomeClass<T> delegate;
  private final U additionalInformation;

  public SomeClassExtended(SomeClass<T> delegate, U additionalInformation) {
    this.delegate = delegate;
    this.additionalInformation = additionalInformation;
  }

  @Override
  public boolean someCondition() {
    return delegate.someCondition();
  }
}

这一切都感觉有点笨拙/臃肿。有没有办法可以更有效地(按地方)共享实现?

0 个答案:

没有答案
相关问题