Search code examples
javabytecodejava-bytecode-asm

Formatting the output of a TraceClassVisitor


Let's say I want to pretty print the bytecode of a method with the asm library.

public int get777() { return 777; }

through TraceClassVisitor will look as

  // access flags 0x1
  public get777()I
   L0
    LINENUMBER 21 L0
    SIPUSH 777
    IRETURN
   L1
    LOCALVARIABLE this Lsomething/Point; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1
}

Now, the thing is that I only care for

    SIPUSH 777
    IRETURN

being everything else largely irrelevant to me, so I want to wipe them out.

I've thought of filtering the stuff I don't want by inheriting TraceMethodVisitor, but it actually turned out to be a final class (bummer!).

Is there any way of formatting the output of a TraceClassVisitor, at all? If not, what would you consider the best approach to filter out the stuff I don't care about?


Solution

  • You can get rid of line numbers and local variables information by passing ClassReader.SKIP_DEBUG flag to ClassReader.accept() method.

    An alternative approach wiuld be to add a visitor before TraceClassVisitor and TraceMethodVisitor that would swallow events you dont want to see in the output.