在下面的代码片段中,我想指定:
-
attachment
和handler
共享一个通用类型 ` -
<A>
的类型只需要在notify()
时指定被调用 - 调用
notify()
是可选的。
我不想强制用户指定 <A>
在类 build 时间,因为他们可能永远不会结束调用 notify()
.
/**
* Builder pattern for some asynchronous operation.
*/
public class OperationBuilder
{
private A attachment = null;
private CompletionHandler<Integer, A> handler = null;
public <A> OperationBuilder notify(A attachment, CompletionHandler<Integer, A> handler)
{
this.attachment = attachment;
this.handler = handler;
return this;
}
public abstract build();
}
这在 Java 下可行吗?如果没有,您会建议我做什么?
更新:我不需要指定 <A>
与 attachment
有关和 handler
必须相同<A>
与 notify()
有关.我要说明的是 attachment
和 handler
必须使用相同的类型 <A>
.
最佳答案
您可以做的最接近的事情是让 notify() 返回一个类型为 A
的桥接对象。沿着这些线的东西:
public class OperationBuilder
{
public Bridge<A> OperationBuilder notify(A a, CompletionHandler<Integer, A> h)
{
return new Bridge<A>(a, h);
}
protected abstract<A> void build(Bridge<A> b);
public class Bridge<A>
{
private A attachment;
private CompletionHandler<Integer, A> handler;
public Bridge(A a, CompletionHandler<Integer, A> h)
{
attachment = a;
handler = h;
}
public void build()
{
build(this); // Will invoke OperationBuilder.build()
}
}
}
关于java - 如何声明字段级类型参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2095627/