Java通用生成器 [英] Java generic builder
问题描述
假设我需要一些 DerivedBuilder
来扩展一些 BaseBuilder
。基本生成器具有类似 foo
的方法(该方法返回 BaseBuilder
)。派生的构建器具有方法 bar
。方法 bar
应该在方法 foo
之后调用。为此,我可以在 DerivedBuilder
中重写 foo
方法,如下所示:
Suppose I need some DerivedBuilder
to extend some BaseBuilder
. Base builder has some method like foo
(which returns BaseBuilder
). Derived builder has method bar
. Method bar
should be invoked after method foo
. In order to do it I can override foo
method in DerivedBuilder
like this:
@Override
public DerivedBuilder foo() {
super.foo();
return this;
}
问题是 BaseBuilder
有很多方法,如 foo
,我必须重写它们中的每一个。我不想这样做,所以我尝试使用泛型:
The problem is that BaseBuilder
has a lot of methods like foo
and I have to override each one of them. I don't want to do that so I tried to use generics:
public class BaseBuilder<T extends BaseBuilder> {
...
public T foo() {
...
return (T)this;
}
}
public class DerivedBuilder<T extends DerivedBuilder> extends BaseBuilder<T> {
public T bar() {
...
return (T)this;
}
}
但是问题是我仍然不能写
But the problem is that I still can not write
new DerivedBuilder<DerivedBuilder>()
.foo()
.bar()
即使 T
此处为 DerivedBuilder
。我该怎么做才能不覆盖很多功能?
Even though T
here is DerivedBuilder
. What can I do in order to not to override a lot of functions?
推荐答案
您的问题是<$ c $的定义c> DerivedBuilder :
class DerivedBuilder<T extends DerivedBuilder>;
然后使用类型为擦除参数 new DerivedBuilder< DerivedBuilder<的实例化它。 ..what?...>>()
。
And then instantiating it with a type erased argument new DerivedBuilder<DerivedBuilder<...what?...>>()
.
您需要一个完全定义的派生类型,例如: / p>
You'll need a fully defined derived type, like this:
public class BaseBuilder<T extends BaseBuilder<T>> {
@SuppressWarnings("unchecked")
public T foo() {
return (T)this;
}
}
public class DerivedBuilder extends BaseBuilder<DerivedBuilder> {
public DerivedBuilder bar() {
return this;
}
}
检查 ideone.com 。
这篇关于Java通用生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!