Java通用生成器

编程入门 行业动态 更新时间:2024-10-25 12:25:24
本文介绍了Java通用生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我需要一些 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?

推荐答案

您的问题是 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 。

更多推荐

Java通用生成器

本文发布于:2023-11-26 21:11:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635209.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:生成器   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!