在Java中这样做是合法的:
void spew(Appendable x)
{
x.append("Bleah!\n");
}我如何做到这一点(语法不合法):
void spew(Appendable & Closeable x)
{
x.append("Bleah!\n");
if (timeToClose())
x.close();
}I希望如果可能的话,强制调用者使用既可附加又可关闭的对象,而不需要特定的类型。有多个标准类可以这样做,例如BufferedWriter、PrintStream等。
如果我定义了我自己的界面
interface AppendableAndCloseable extends Appendable, Closeable {}这是行不通的,因为实现Appendable和Closeable的标准类不实现我的接口AppendableAndCloseable (除非我不像我认为的那样理解.空接口仍然在它们的超级接口之外添加唯一性)。
我能想到的最接近的方法是做以下工作之一:
instanceof。缺点:编译时没有捕捉到问题。void (可附加xAppend,可关闭xClose) { xAppend.append("Bleah!\n");if (timeToClose()) xClose.close();}
发布于 2009-09-30 22:00:34
你可以用泛型来做:
public <T extends Appendable & Closeable> void spew(T t){
t.append("Bleah!\n");
if (timeToClose())
t.close();
}实际上,你的语法几乎是正确的。
https://stackoverflow.com/questions/1500827
复制相似问题