title: What is the proper way to stack ASM visitors?
body: <p>I have the following code:</p>
  
  <pre><code>for (Map.Entry&lt;String, ClassReader&gt; e : classes.entrySet())
  {
      ClassReader reader = e.getValue();
      ClassWriter writer = new ClassWriter(Opcodes.ASM7);
  
      // Process all visitors
      reader.accept(new StringRemapper(writer, "String A", "String A!!"), ClassReader.EXPAND_FRAMES);
      reader.accept(new StringRemapper(writer, "String B", "String B!!"), ClassReader.EXPAND_FRAMES);
  
      // Update the class
      reader = new ClassReader(writer.toByteArray());
      e.setValue(reader);
  }
  </code></pre>
  
  <p>The issue with the code above is that it is writing everything twice, because there are two visitors writing to the same writer (I guess).</p>
  
  <p>To fix this issue, I need to add the code below after every <code>reader.accept</code>:</p>
  
  <pre><code>reader = new ClassReader(writer.toByteArray());
  writer = new ClassWriter(Opcodes.ASM7);
  </code></pre>
  
  <p>The thing is, by doing so, am I misusing the visitor pattern? I mean, why do I need to create a new reader/writer and <strong>visit it only once</strong>? Shouldn't I be able to have multiple visitors?</p>
  
  <p>I found this similar question <a href="https://stackoverflow.com/questions/7947484/easy-way-to-stack-up-a-couple-of-asm-bytecode-visitors">Easy way to stack up a couple of ASM-Bytecode visitors?</a> but couldn't understand the accepted answer. </p>
  
  <p>I tried to pass the first visitor as a parameter to the second instead of the original ClassWriter, had the same result, duplicated code.</p>
  
  <pre><code>ClassVisitor last;
  // Process all visitors
  reader.accept(last = new StringRemapper(writer, "String A", "String A!!"), ClassReader.EXPAND_FRAMES);
  reader.accept(new StringRemapper(last, "String B", "String B!!"), ClassReader.EXPAND_FRAMES);
  </code></pre>