如何在Java中使用方法参数来实现多个接口? [英] How can I require a method argument in Java to implement multiple interfaces?

查看:1034
本文介绍了如何在Java中使用方法参数来实现多个接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中执行此操作是合法的:

It's legal to do this in 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();
 }

我希望尽可能强制调用者使用可附加和可关闭,无需特定类型。有多个标准类可以执行此操作,例如BufferedWriter,PrintStream等

I would like if possible to force callers to use objects that are both Appendable and Closeable, without requiring a specific type. There are multiple standard classes that do this, e.g. BufferedWriter, PrintStream, etc.

如果我定义自己的界面

 interface AppendableAndCloseable extends Appendable, Closeable {}

自实现Appendable的标准类以来不起作用和Closeable不实现我的接口AppendableAndCloseable(除非我不理解Java以及我认为我做...空接口仍然在其超级接口之外添加唯一性)。

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).

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

The closest I can think of is to do one of the following:


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

  1. pick one interface (e.g. Appendable), and use runtime tests to ensure the argument is an instanceof the others. Downside: problem not caught at compile time.

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

require multiple arguments (catches compile-time correctness but looks dorky):

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中使用方法参数来实现多个接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆