简体   繁体   English

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

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

It's legal to do this in Java: 在Java中执行此操作是合法的:

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

How can I do this (syntax not legal): 我该怎么做(语法不合法):

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

I would like if possible to force callers to use objects that are both Appendable and Closeable, without requiring a specific type. 我希望尽可能强制调用者使用Appendable和Closeable的对象,而不需要特定的类型。 There are multiple standard classes that do this, eg BufferedWriter, PrintStream, etc. 有多个标准类可以执行此操作,例如BufferedWriter,PrintStream等。

If I define my own interface 如果我定义自己的界面

 interface AppendableAndCloseable extends Appendable, Closeable {}

that won't work since the standard classes that implement Appendable and Closeable do not implement my interface AppendableAndCloseable (unless I don't understand Java as well as I think I do... empty interfaces still add uniqueness above and beyond their superinterfaces). 因为实现Appendable和Closeable的标准类没有实现我的接口AppendableAndCloseable(除非我不理解Java以及我认为我做的...空接口仍然在其超级接口之上和之外添加唯一性),这将无法工作。

The closest I can think of is to do one of the following: 我能想到的最接近的是做以下其中一项:

  1. pick one interface (eg Appendable), and use runtime tests to ensure the argument is an instanceof the others. 选择一个接口(例如Appendable),并使用运行时测试来确保参数是其他参数的instanceof Downside: problem not caught at compile time. 缺点:编译时没有遇到问题。

  2. require multiple arguments (catches compile-time correctness but looks dorky): 需要多个参数(捕获编译时正确但看起来很笨):

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

You could do it with generics: 你可以用泛型来做到这一点:

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

Your syntax was almost right, actually. 实际上,你的语法几乎是正确的。

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

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