首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将java.lang.Appendable包装成java.io.Writer?

如何将java.lang.Appendable包装成java.io.Writer?
EN

Stack Overflow用户
提问于 2014-01-18 05:30:16
回答 2查看 4.5K关注 0票数 3

UPDATE2:我自己版本的适配器类,它只在构造函数中调用instanceof,并且在flush()close()函数中使用一个(Java1.5)增量(避免在对象构造之后需要任何反射或逻辑)。UPDATE1:写了一个简单的适配器,这正是我所需要的。包括以下内容。最初的问题如下。

需要java.lang.Appendable的函数可以接受java.io.Writer,因为Writer实现了Appendable

那另一个方向呢?我正在使用一个需要编写器的函数,我试图创建另一个调用它的函数,它接受一个附录并将它传递给原始的编写器函数。

我看到您可以扩展Writer (这是抽象的),并将所有write(...)函数重定向到相应的append(...)-s。但是您还必须实现flush()close(),我很清楚如何清晰地编写这些代码,这样这个包装器类就可以接受任何附件。

我很惊讶没有任何东西已经存在,无论是在网络上,还是在堆栈溢出上,或者在现有的库中,都可以解决这个问题。至少我找不到。

我希望你能给我一点指导。谢谢。

回答此问题的适配器代码。作者(我自己的版本如下):

代码语言:javascript
复制
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
import java.io.Writer;

public class AppendableWriterAdapter extends Writer {

      private Appendable appendable;

      public AppendableWriterAdapter(Appendable appendable) {
            this.appendable = appendable;
      }

      @Override
      public void write(char[] cbuf, int off, int len) throws IOException {
            appendable.append(String.valueOf(cbuf), off, len);
      }

      @Override
      public void flush() throws IOException {
            if (appendable instanceof Flushable) {
                  ((Flushable) appendable).flush();
            }
      }

      @Override
      public void close() throws IOException {
            flush();
            if (appendable instanceof Closeable) {
                  ((Closeable) appendable).close();
            }
      }

}

下面是我自己的版本,基于Marc,它只在构造函数中使用instanceof,在flush()close()中使用(Java1.5)增量。这是为了避免在对象构造之后使用任何逻辑或反射。这也是作为一个要旨https://gist.github.com/aliteralmind/8494917发布的。

这个类包含一个演示,后面是两个不需要做的增量(一个Flushable,一个Closeable),主函数(newWriterForAppendable(apbl)),然后是适配器类本身。

代码语言:javascript
复制
   import  java.io.Closeable;
   import  java.io.Flushable;
   import  java.io.IOException;
   import  java.io.Writer;
/**
   <P>{@code java NewWriterForAppendable}.</P>
 **/
public class NewWriterForAppendable  {
   /**
      <P>Demonstrates {@code newWriterForAppendable(apbl)} for creating a new {@code Writer} that wraps around {@code System.out} (writes to the console).</P>
    **/
   public static final void main(String[] igno_red)  {
      try  {
         NewWriterForAppendable.newWriterForAppendable(System.out).write("hello");
      }  catch(IOException iox)  {
         throw  new RuntimeException("WriterForAppendableXmpl", iox);
      }
   }
   /**
      <P>A {@code Flushable} whose {@code flush()} function does nothing. This is used by {@link #newWriterForAppendable(Appendable ap_bl) newWriterForAppendable}{@code (apbl)} as a (Java 1.5) delta.</P>

      @see  #newWriterForAppendable(Appendable) newWriterForAppendable(apbl)
    **/
   public static final Flushable FLUSHABLE_DO_NOTHING = new Flushable()  {
      public void flush()  {
      }
   };
   /**
      <P>A {@code Closeable} whose {@code close()} function does nothing. This is used by {@link #newWriterForAppendable(Appendable ap_bl) newWriterForAppendable}{@code (apbl)} as a (Java 1.5) delta.</P>

      @see  #newWriterForAppendable(Appendable) newWriterForAppendable(apbl)
    **/
   public static final Closeable CLOSEABLE_DO_NOTHING = new Closeable()  {
      public void close()  {
      }
   };
   /**
      <P>Creates a new {@code java.io.Writer} that wraps around a {@code java.lang.Appendable}. It properly {@link java.io.Writer#flush() flush}es and {@link java.io.Writer#close() close}s appendables that happened to also be {@link java.io.Flushable}s and/or {@link java.io.Closeable Closeable}s. This uses {@code instanceof} only in the constructor, and a delta in {@code flush()} and {@code close()}, which avoids having to use any logic or reflection after object construction.</P>

      <P>This function is released as a <A HREF="https://gist.github.com/aliteralmind/8494917">gist</A>, and is an example of the <A HREF="http://en.wikipedia.org/wiki/Adapter_pattern#Object_Adapter_pattern">Object Adapter pattern</A>. Thanks to <A HREF="http://stackoverflow.com/users/1211906/marc-baumbach">Marc Baumbach</A> on <A HREF="http://stackoverflow.com">{@code stackoverflow}</A> for the assistance. See (viewed 1/18/2014)
      <BR> &nbsp; &nbsp; <CODE><A HREF="http://stackoverflow.com/questions/21200421/how-to-wrap-a-java-lang-appendable-into-a-java-io-writer">http://stackoverflow.com/questions/21200421/how-to-wrap-a-java-lang-appendable-into-a-java-io-writer</A></CODE></P>

      @return  A new writer that uses an appendable to do its output.
      @see  #FLUSHABLE_DO_NOTHING
      @see  #CLOSEABLE_DO_NOTHING
    **/
   public static final Writer newWriterForAppendable(Appendable ap_bl)  {
      return  (new WFA(ap_bl));
   }
   private NewWriterForAppendable()  {
      throw  new IllegalStateException("constructor: Do not instantiate.");
   }
}
class WFA extends Writer  {
   private final Appendable apbl;
   private final Flushable  flbl;
   private final Closeable  clbl;
   public WFA(Appendable ap_bl)  {
      if(ap_bl == null)  {
         throw  new NullPointerException("ap_bl");
      }
      apbl = ap_bl;

      //Avoids instanceof at every call to flush() and close()
      flbl = (Flushable)((ap_bl instanceof Flushable) ? ap_bl
         :  NewWriterForAppendable.FLUSHABLE_DO_NOTHING);
      clbl = (Closeable)((ap_bl instanceof Closeable) ? ap_bl
         :  NewWriterForAppendable.CLOSEABLE_DO_NOTHING);
   }
   @Override
   public void write(char[] a_c, int i_ndexStart, int i_ndexEndX) throws IOException {
      apbl.append(String.valueOf(a_c), i_ndexStart, i_ndexEndX);
   }
   @Override
   public Writer append(char c_c) throws IOException {
      apbl.append(c_c);
      return  this;
   }
   @Override
   public Writer append(CharSequence c_q) throws IOException {
      apbl.append(c_q);
      return  this;
   }
   @Override
   public Writer append(CharSequence c_q, int i_ndexStart, int i_ndexEndX) throws IOException  {
      apbl.append(c_q, i_ndexStart, i_ndexEndX);
      return  this;
   }
   @Override
   public void flush() throws IOException {
      flbl.flush();
   }
   @Override
   public void close() throws IOException {
      flush();
      clbl.close();
   }

}
EN

回答 2

Stack Overflow用户

发布于 2014-01-18 05:43:32

您可以接受任何Appendable,然后通过instanceof检查它是否是Writer。然后进行向下转换,并调用只接受Writer的函数。

示例:

代码语言:javascript
复制
public void myMethod(Appendable app) throws InvalidAppendableException {

   if (app instanceof Writer) {
      someObj.thatMethod((Writer) app);
   } else {
      throw new InvalidAppendableException();
   }
}
票数 0
EN

Stack Overflow用户

发布于 2016-04-10 12:36:13

谷歌的番石榴有一个简单的实用工具可以做到这一点:CharStreams.asWriter

实现不是最快的(看见),如果您想获得最好的性能,可能需要查看spf4j Streams.asWriter

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21200421

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档