53

在 Java 中这样做是合法的:

 void spew(Appendable x)
 {
     x.append("Bleah!\n");
 }

我该怎么做(语法不合法):

 void spew(Appendable & Closeable x)
 {
     x.append("Bleah!\n");
     if (timeToClose())
         x.close();
 }

如果可能的话,我希望强制调用者使用可附加和可关闭的对象,而不需要特定的类型。有多个标准类可以做到这一点,例如 BufferedWriter、PrintStream 等。

如果我定义自己的界面

 interface AppendableAndCloseable extends Appendable, Closeable {}

这是行不通的,因为实现 Appendable 和 Closeable 的标准类没有实现我的接口 AppendableAndCloseable (除非我不像我认为的那样理解 Java……空接口仍然在它们的超级接口之上和之外添加唯一性)。

我能想到的最接近的是执行以下操作之一:

  1. 选择一个接口(例如 Appendable),并使用运行时测试来确保参数是instanceof其他接口。缺点:在编译时没有发现问题。

  2. 需要多个参数(捕获编译时正确性但看起来很笨拙):

    void spew(Appendable xAppend, Closeable xClose)
    {
        xAppend.append("Bleah!\n");
        if (timeToClose())
            xClose.close();
    }
    
4

1 回答 1

86

你可以用泛型来做到这一点:

public <T extends Appendable & Closeable> void spew(T t){
    t.append("Bleah!\n");
    if (timeToClose())
        t.close();
}

实际上,您的语法几乎是正确的。

于 2009-09-30T22:00:34.077 回答