UPDATE2: My own version of the adapter class, that only calls instanceof
in the constructor and uses a (Java 1.5) delta in the flush()
and cl
Google's Guava has a simple utility to do this: CharStreams.asWriter
The implementation is not the fastest (see), if you want the best performance, you might want to look at spf4j Streams.asWriter
You can accept any Appendable
and then check if it is a Writer
through instanceof
. Then do a downcast and call that function that accepts only Writer
.
example:
public void myMethod(Appendable app) throws InvalidAppendableException {
if (app instanceof Writer) {
someObj.thatMethod((Writer) app);
} else {
throw new InvalidAppendableException();
}
}
Typically in a Writer
, the flush()
and close()
are there to cleanup any additional writes that may not have been committed or sent to the stream. By simply redirecting all of the write
methods directly to the append
methods in the Appendable
you won't have to worry about flush()
and close()
unless your Appendable
implements Closeable
and/or Flushable
.
A good example is something like BufferedWriter. When you are calling write()
on that, it may not be sending all of the bytes to the final output/stream immediately. Some bytes may not be sent until you flush()
or close()
it. To be absolutely safe, I would test the wrapped Appendable
if it is Closeable
or Flushable
in the corresponding method and cast it and perform the action as well.
This is a pretty standard design pattern called the Adapter pattern.
Here is what is likely a good implementation for this adapter: http://pastebin.com/GcsxqQxj