下面列出了怎么用org.objectweb.asm.tree.analysis.BasicInterpreter的API类实例代码及写法,或者点击链接到github查看源代码。
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void removeDeadCode(ClassNode cn, MethodNode mn) {
Analyzer analyzer = new Analyzer(new BasicInterpreter());
try {
analyzer.analyze(cn.name, mn);
} catch (AnalyzerException e) {
ErrorDisplay.error("Could not analyze the code: " + e.getMessage());
return;
}
Frame[] frames = analyzer.getFrames();
AbstractInsnNode[] insns = mn.instructions.toArray();
for (int i = 0; i < frames.length; i++) {
AbstractInsnNode insn = insns[i];
if (frames[i] == null && insn.getType() != AbstractInsnNode.LABEL) {
mn.instructions.remove(insn);
insns[i] = null;
}
}
}
public ConstructorThisInterpreter() {
super(Opcodes.ASM6);
this.underlying = new BasicInterpreter();
// NOTE: This is based on the assumption that a non-static method's first newValue() call is for "this".
this.isNextThis = true;
}
public PopAnalyzer(AbstractInsnNode node) {
super(new BasicInterpreter());
this.node = node;
}
@Override
public MethodVisitor visitMethod(final int access, final String name,
final String desc, final String signature, final String[] exceptions)
{
// Unused?
/*
final MethodVisitor mv = super.visitMethod(access, name, desc,
signature, exceptions);
*/
return new MethodNode(Opcodes.ASM5, access, name, desc, signature,
exceptions)
{
@Override
public void visitEnd()
{
super.visitEnd();
try {
final BasicInterpreter basicInterpreter
= new BasicInterpreter();
final Analyzer<BasicValue> analyzer
= new Analyzer<>(basicInterpreter);
final AbstractInsnNode[] nodes = instructions.toArray();
final Frame<BasicValue>[] frames
= analyzer.analyze(className, this);
int areturn = -1;
for (int i = nodes.length -1; i >= 0; i--)
{
if (nodes[i].getOpcode() == Opcodes.ARETURN) {
areturn = i;
System.out.println(className + "." + name + desc);
System.out.println("Found areturn at: " + i);
} else if (areturn != -1
&& nodes[i].getOpcode() != -1
&& frames[i].getStackSize() == 0) {
System.out.println("Found start of block at: " + i);
final InsnList list = new InsnList();
for (int j = i; j <= areturn; j++)
list.add(nodes[j]);
final Textifier textifier = new Textifier();
final PrintWriter pw = new PrintWriter(System.out);
list.accept(new TraceMethodVisitor(textifier));
textifier.print(pw);
pw.flush();
System.out.println("\n\n");
areturn = -1;
}
}
}
catch (AnalyzerException e) {
e.printStackTrace();
}
if (mv != null)
accept(mv);
}
};
}