Java - 继承Fluent方法返回类型以返回事件类的类型,而不是父类 [英] Java - Inherited Fluent method return type to return incident class' type, not parent's

查看:159
本文介绍了Java - 继承Fluent方法返回类型以返回事件类的类型,而不是父类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您采用流畅的方法时,您可能会遇到以下情况:

When you employ a fluent approach you might have the following scenario:

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{}

一个流畅的接口的优点是你可以链接方法调用,但是当Bar继承了someMethod()时,返回类型是Foo not会破坏以下链条的栏:

A strength of a fluent interface is that you can chain method invocations, but whilst Bar has inherited someMethod(), the return type is Foo not Bar which would break the following chain:

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

一个答案可能是为每个继承的方法添加@Overrides,这样Bar就有了额外的方法:

One answer could be to add @Overrides for every inherited method, such that Bar has the additional method:

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

但是在大​​型类和扩展类层次结构中,这可以证明一堆乱七八糟的冗余一定?!是否有适当的返回类型来提供流畅的方法,其中每个继承它的类都将返回其特定类型的对象(以便我们可以链接没有强制转换的方法)?

But in large classes, and extended class hierarchies this can prove a mess of redundancy surely?! Is there an appropriate return type to give to fluent methods whereby every class that inherits it will return an object of its specific type (so that we can chain methods without casts)?

我试过:

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

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

To alas, no avail. I am hoping someone knows of a simple and elegant solution to this problem. The project is large and so it needs to be maintainable and extensible if possible.

感谢您在此方案中提供的任何帮助。

Thank you to any help you can provide in this scenario.

推荐答案

你可以这样做,如果你不介意未选中的演员:

You can do it like this, if you don't mind an unchecked cast:

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;
  }
}

就我个人而言,我全局禁用未经检查的投射警告整个项目。

Personally, I disable the unchecked cast warning globally for the whole project.

这篇关于Java - 继承Fluent方法返回类型以返回事件类的类型,而不是父类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆