繁体   English   中英

如何在Java中使用方法参数来实现多个接口?

[英]How can I require a method argument in Java to implement multiple interfaces?

在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以及我认为我做的...空接口仍然在其超级接口之上和之外添加唯一性),这将无法工作。

我能想到的最接近的是做以下其中一项:

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM