1

Using ASM, I need to modify a method, then I need to insert two methods into it. I have gotten the modification fine, but how to I create a method? Do I need a separate MethodVisitor, or can I use the same one, but call something else?

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
JD9999
  • 394
  • 1
  • 7
  • 18

1 Answers1

4

You need to call visitMethod on the corresponding ClassWriter to create a new MethodVisitor for each method.

A MethodVisitor cannot be reused. If you want to insert a method into an existing class, you typically do that from the visitEnd method of the ClassVisitor reading the original class file.

A schematic of such a transformation would look like this:

class TransformingClassVisitor extends ClassVisitor {
  TransformingClassVisitor(ClassVisitor cv) { super(Opcodes.ASM5, cv); }

  @Override
  public MethodVisitor visitMethod(int opcode, String name, String owner, String desc, String signature, boolean iFace) {
    MethodVisitor mv = super.visitMethod(opcodes, name, owner, desc, signature, iFace);
    if (<isTransformedMethod>) {
      return new TransformingMethodVisitor(mv);
    }
    return mv;
  }

  @Override
  public void visitEnd() {
    MethodVisitor m1 = super.visitMethod(<firstMethod>);
    implement1(m1);

    MethodVisitor m2 = super.visitMethod(<secondMethod>);
    implement1(m2);

    super.visitEnd();
  }
}
Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
  • So my ClassVisitor will have the visitEnd() method. My file needs to add two methods. Would I have three MethodVisitors then: One for the code I'm inserting into the method, and two more for the two methods I want to insert? But will I only need one ClassVisitor? – JD9999 Mar 14 '16 at 04:33
  • You would need to implement one MethodVisitor that modifies the original code by wrapping the "super" method visitor. From the VisitEnd method of the ClassVisitor that wrapps the ClassWriter you then call visitMethod twice and insert the code directly on the returned MethodVisitor. – Rafael Winterhalter Mar 14 '16 at 07:25
  • So do I need 3 MethodVisitors? But only 1 ClassVisitor in which I call the visitEnd() method twice? – JD9999 Mar 14 '16 at 08:10
  • I added a schematic to my answer. – Rafael Winterhalter Mar 14 '16 at 08:43