java有生成器吗,Java通用生成器

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;

}

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 {

...

public T foo() {

...

return (T)this;

}

}

public class DerivedBuilder extends BaseBuilder {

public T bar() {

...

return (T)this;

}

}

But the problem is that I still can not write

new DerivedBuilder()

.foo()

.bar()

Even though T here is DerivedBuilder. What can I do in order to not to override a lot of functions?

解决方案

Your problem is the definition of DerivedBuilder:

class DerivedBuilder;

And then instantiating it with a type erased argument new DerivedBuilder>().

You'll need a fully defined derived type, like this:

public class BaseBuilder> {

@SuppressWarnings("unchecked")

public T foo() {

return (T)this;

}

}

public class DerivedBuilder extends BaseBuilder {

public DerivedBuilder bar() {

return this;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值