I have the following code:
for (Map.Entry<String, ClassReader> 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);
}
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).
To fix this issue, I need to add the code below after every reader.accept
:
reader = new ClassReader(writer.toByteArray());
writer = new ClassWriter(Opcodes.ASM7);
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 visit it only once? Shouldn't I be able to have multiple visitors?
I found this similar question Easy way to stack up a couple of ASM-Bytecode visitors? but couldn't understand the accepted answer.
I tried to pass the first visitor as a parameter to the second instead of the original ClassWriter, had the same result, duplicated 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);