Java - 继承的 Fluent 方法返回类型,用于返回事件类的类型,而不是父类的类型



当您采用流利的方法时,您可能会有以下方案:

public class Foo<T extends a>{
    public Foo<T> someMethod(){
          System.out.println("foo");
          return this;
    }
}

public class Bar<T extends b> extends Foo<T> {
         public Bar<T> barMethod(){
            System.out.println("bar");
            return this;
         }
}

public class a{}
public class b extends a{}

fluent接口的强度是您可以链方法调用,但是虽然bar已继承了somemethod(),但返回类型是foo not bar,它会破坏以下链:

new Bar<b>().someMethod().barMethod();

一个答案可能是为每种继承方法添加@overrides,以便bar具有其他方法:

 @Override
 public Bar<T> someMethod(){
          System.out.println("foo");
          return this;
    }

但是,在大型课程中,并且扩展类层次结构这肯定会证明一团糟吗?是否有适当的返回类型可以给予流利的方法,因此每个继承的类都会返回其特定类型的对象(以便我们可以链接无铸件的方法)?

我尝试了:

        public <U extends Foo<T>> U someMethod(){
          System.out.println("foo");
          return this;
    }

a a,无济于事。我希望有人知道这个问题的简单而优雅的解决方案。该项目很大,因此,如果可能的话,必须可维护和扩展。

感谢您在这种情况下可以提供的任何帮助。

您可以这样做,如果您不介意不受控制的演员:

public class Foo<T, F extends Foo<T, F>> {
  public F someMethod() {
    System.out.println("foo");
    return (F) this; // <--- That's the unchecked cast! Tucked safely away.
  }
  public static void main(String[] args) {
    new Bar<String>().someMethod().barMethod();
  }
}
class Bar<T> extends Foo<T, Bar<T>> {
  public Bar<T> barMethod() {
    System.out.println("bar");
    return this;
  }
}

就我个人而言,我禁用了整个项目的全球未检查的铸造警告。

您可以做的是定义barMethod方法摘要,因此现在您可以在Foo类型上调用它。

public abstract class Foo<T extends a> {
    public Foo<T> someMethod() {
        System.out.println("foo");
        return this;
    }
    public abstract Foo<T> barMethod();
}

现在您可以轻松致电

new Bar<b>().someMethod().barMethod();

最新更新