编程语言
首页 > 编程语言> > 如何在Java中使用方法参数来实现多个接口?

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

作者:互联网

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),并使用运行时测试来确保参数是其他参数的实例.缺点:编译时没有遇到问题.
>需要多个参数(捕获编译时正确但看起来很笨):

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();
}

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

标签:java,oop,multiple-inheritance
来源: https://codeday.me/bug/20190928/1827173.html