2 回答

TA贡献1886条经验 获得超2个赞
从构造函数MethodNode(int access, String name, String descriptor, String signature, String[] exceptions)的文档中:
...子类不得使用此构造函数。相反,他们必须使用MethodNode(int, int, String, String, String, String[])版本。
由于您正在创建一个子类,因此您必须更改调用
new MethodNode(access, name, desc, signature, exceptions) {
…
}
到
new MethodNode(ASM7, access, name, desc, signature, exceptions) {
…
}

TA贡献1844条经验 获得超8个赞
只是为了提供一个完整的运行样本来检测main()给定类的函数
public class Instrumentation {
public byte[] instrument(String className) {
byte[] modifiedClass = null;
try {
ClassReader classReader = new ClassReader(className);
ClassWriter classWriter = new ClassWriter(classReader, 4);
ClassVisitor classVisitor = new ClassVisitor(ASM7) {
public MethodVisitor visitMethod(
int access,
String name,
String desc,
String signature,
String[] exceptions) {
if (name.equals("main")) {
MethodNode methodNode = new MethodNode(ASM7,access, name, desc, signature, exceptions) {
public void visitEnd() {
// do some stuff here; remove exceptions, insnnode etc. -- smaple iterates through instructions
for (int i = 0; i < this.instructions.size();i++) {
AbstractInsnNode node = this.instructions.get(i);
}
}
};
return methodNode;
} else {
return super.visitMethod(access, name, desc, signature, exceptions);
}
}
};
classReader.accept(classVisitor,0);
classReader.accept(classWriter, 0);
modifiedClass = classWriter.toByteArray();
} catch (IOException ex) {
// handle IOException here
}
return modifiedClass;
}
}
添加回答
举报