我想编写Java代码(比如一个方法),用于打印一些行。调用者提供要打印的对象。我希望我的代码不关心该对象的具体内容,只需调用该对象的println()或println(String)方法即可。它应该适用于java.io.PrintStream(例如System.out)或java.io.PrintWriter(例如由调用者使用new PrintWriter(System.out)或new PrintWriter(new ByteArrayOutputStream())构造的对象)。如果“printlineable”对象的潜在类共享某个接口,强制执行println()和println(String)方法,则这将很容易。但是它们没有。那么我在签名中放什么来接收这样的对象,而不违反DRY原则(当我简单地重载该函数时必须交换实现的类型)?
public void sayHello( ??? outThingy) {
outThingy.println("Hello World");
outThingy.println();
// This just a minimal example.
// The real implementation might be more involved
// and non-trivial, so that avoiding duplication
// becomes a real concern.
};
// sayHello should be usable like this:
sayHello(System.out);
// but also like this:
baos = new ByteArrayOutputStream();
pw = new PrintWriter(baos)
sayHello(pw);
pw.flush();
System.out.println(baos.toString());
或者说,PrintStream
和PrintWriter
没有共享这样一个接口的事实,应该被视为它们在提供打印行的方式上不可互换的指示吗?(而不是在这些类被指定时存在某种历史疏忽。)
void sayHello(PrintStream out) { PrintWriter pw = new PrintWriter(out); sayHello(pw); pw.flush(); }
,然后实现void sayHello(PrintWriter out)
方法。 - Andreasprintln()
而无需任何包装,但也许这是不可能的,除非对调用者施加新接口,当前Java标准库类没有实现。 - das-g