How to wrap a java.lang.Appendable into a java.io.Writer?

前端 未结 3 884
没有蜡笔的小新
没有蜡笔的小新 2020-12-21 08:37

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

相关标签:
3条回答
  • 2020-12-21 09:14

    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

    0 讨论(0)
  • 2020-12-21 09:17

    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();
       }
    }
    
    0 讨论(0)
  • 2020-12-21 09:26

    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

    0 讨论(0)
提交回复
热议问题