public class ChainingVisitors {
public static void main(String[] args) throws Exception {
ClassReader reader = new ClassReader("com.foo.Bar");
ClassWriter writer = new ClassWriter(COMPUTE_MAXS | COMPUTE_FRAMES);
ClassVisitor v3 = new Link(3, writer);
ClassVisitor v2 = new Link(2, v3);
ClassVisitor v1 = new Link(1, v2);
reader.accept(v1, 0);
System.out.printf("how many bytes in %s? %d\n", Runnable.class, writer.toByteArray().length);
}
private static class Link extends ClassVisitor {
private final int order;
public Link(int order, ClassVisitor next) {
super(ASM4, next);
this.order = order;
}
@Override public void visit(int i, int i2, String s, String s2, String s3, String[] strings) {
System.out.printf("In visitor %d\n", order);
super.visit(i, i2, s, s2, s3, strings);
}
}
I'd like to hand an arbitrary chain of ClassVisitor
s off to a method. That method would read in the bytes of a class via a ClassReader
, transform the class using the ClassVisitors
in turn, and write the result via a ClassWriter
. Basically, I want to use a chain of these visitors (which, let's assume, I don't control) "in between" a ClassReader
and ClassWriter
, whose instantiation the method would control.
How can I do this? It seems as though the chaining of visitors wants you to build the chain from "back" (last link, tied to a ClassWriter
) to "front" (first link, accept()
ed by a ClassReader
).