在Java中,这样做是合法的:
void spew(Appendable x)
{
x.append("Bleah!\n");
}
我该如何做到这一点(语法不合法):
void spew(Appendable & Closeable x)
{
x.append("Bleah!\n");
if (timeToClose())
x.close();
}
如果可能的话,我想强制调用者使用既是Appendable又是Closeable的对象,而不需要指定特定类型。有多个标准类可以做到这一点,例如BufferedWriter、PrintStream等。
如果我定义自己的接口
interface AppendableAndCloseable extends Appendable, Closeable {}
由于实现Appendable和Closeable标准类并没有实现我定义的接口AppendableAndCloseable(除非我对Java的理解不如我想象的那么好...即使是空接口,它们仍然超越其超级接口而具有独特性),所以这样做行不通。
我能想到的最接近的方法是执行以下操作之一:
选择一个接口(例如Appendable),并使用运行时测试来确保参数是其他接口的
instanceof
。 缺点:问题无法在编译时捕获。需要多个参数(可以在编译时捕获错误,但看起来很笨拙):
void spew(Appendable xAppend, Closeable xClose) { xAppend.append("Bleah!\n"); if (timeToClose()) xClose.close(); }