Java:在超类方法签名中返回子类 [英] Java: returning subclass in superclass method signature
问题描述
我正在解决一个问题,其中有几个 Foo
的实现,伴随着几个 FooBuilder
的。虽然 Foo
分享了几个需要设置的常见变量,但它们也有不同的变量需要各自的 FooBuilder
实现一些特定的功能。为了简洁,我想让 FooBuilder
的setter使用方法链,例如:
I'm working on a problem where there are several implementations of Foo
, accompanied by several FooBuilder
's. While Foo
's share several common variables that need to be set, they also have distinct variables that require their respective FooBuilder
to implement some specific functionality. For succinctness, I'd like to have the FooBuilder
's setters to use method chaining, like:
public abstract class FooBuilder {
...
public FooBuilder setA(int A) {
this.A = A;
return this;
}
...
}
和
public class FooImplBuilder extends FooBuilder{
...
public FooImplBuilder setB(int B) {
this.B = B;
return this;
}
public FooImplBuilder setC(int C) {
this.C = C;
return this;
}
...
}
等等,与几个不同的 FooBuilder
实现。这在技术上完成了我想要的一切,但是,这种方法对执行方法链接时方法调用的顺序很敏感。以下是方法未定义的编译错误:
And so on, with several different FooBuilder
implementations. This technically does everything I want, however, this approach is sensitive to the order of methods calls when method chaining is performed. The following has method undefined compile errors:
someFoo.setA(a).setB(b)...
要求开发人员考虑链中方法调用的顺序。为了避免这种情况,我想让 FooBuilder
中的setter以某种方式返回实际的实现子类。但是,我不知道该怎么做。什么是最好的方法?
Requiring that the developer think about the order of method calls in the chain. To avoid this, I'd like to have the setters in FooBuilder
somehow return the actual implementing subclass. However, I'm not sure how to do this. What is the best approach?
推荐答案
这是一个很好的问题,也是一个真正的问题。
This is a good question and a real problem.
在Jochen的回答中提到,在Java中处理它的最简单方法可能是使用泛型。
The easiest way to deal with it in Java likely involves the use of generics, as mentioned in Jochen's answer.
这个问题有一个很好的讨论和合理的解决方案。关于使用带有Fluent接口的继承的博客文章在构建器子类中定义 getThis()
方法的泛型,以解决始终返回正确类的构建器的问题。
There's a good discussion of the issue and a reasonable solution in this blog entry on Using Inheritance with Fluent Interfaces, which combines generics with the definition of a getThis()
method overriden in builder subclasses to solve the problem of always returning a builder of the correct class.
这篇关于Java:在超类方法签名中返回子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!