我有以下代码
public class ComplicatedBuilder extends MyBuilder
{
public final Parameter<ComplicatedBuilder, Long> par1 = new Parameter<>(this);
public final Parameter<ComplicatedBuilder, Long> par2 = new Parameter<>(this);
...
}
public class Parameter<B extends MyBuilder, T>
{
private T val;
private B builder;
public Parameter(B b)
{
builder = b;
}
public B setValue(T v)
{
val = v;
return builder;
}
...
}
//usage:
ComplicatedBuilder builder = new ComplicatedBuilder();
builder
.par1.setValue(5)
.par2.setValue(7);
如何使用public final Parameter<this.class, Long> par1 ...
之类的参数声明参数?我希望以允许将参数列表复制粘贴到另一个构建器而不需要进行大量更改的方式进行。
答案 0 :(得分:2)
abstract class AbstractComplicatedBuilder<B extends AbstractComplicatedBuilder<B>>
extends MyBuilder {
public final Parameter<B, Long> par1 = new Parameter<>(self());
public final Parameter<B, Long> par2 = new Parameter<>(self());
abstract B self();
}
class ComplicatedBuilder extends AbstractComplicatedBuilder<ComplicatedBuilder>{
ComplicatedBuilder self(){
return this;
}
}
您可以使用通用参数AbstractComplicatedBuilder
来推迟构建实际B extends AbstractComplicatedBuilder<B>
。