如何用java创建接口i,如何在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();

}

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.

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

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

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

}

解决方案

You could do it with generics:

public void spew(T t){

t.append("Bleah!\n");

if (timeToClose())

t.close();

}

Your syntax was almost right, actually.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值