Formatting the output of a TraceClassVisitor

2019-07-23 21:01发布

问题:

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?

回答1:

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.



回答2:

I would look at providing my own Printer (perhaps extending or delegating to Textifier) via the TraceClassVisitor(ClassVisitor,Printer,PrintWriter) constructor. I haven't tested this approach.



回答3:

My standard approach: Get the source code, search'n'replace final class -> class, recompile.