ASM访客者模式

ASM访客者

is = new FileInputStream(classFile);
ClassReader classReader = new ClassReader(is);
ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
ClassVisitor classVisitor = new TraceClassAdapter(Opcodes.ASM5, classWriter);
classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES);
is.close();

if (output.isDirectory()) {
    os = new FileOutputStream(changedFileOutput);
} else {
    os = new FileOutputStream(output);
}
os.write(classWriter.toByteArray());
os.close();

classReader用来读取来自inputstream的class字节码,并在遍历到类和方法时分别调用到visit和visitMethod方法,参数为解析出的信息


graph LR
FileInputStream-->classReader
classReader-->ClassVisitor
ClassVisitor-->ClassWriter
ClassWriter-->FileOutputStream


@Override
public MethodVisitor visitMethod(int access, String name, String desc,
                                 String signature, String[] exceptions) {

在方法开始处插桩AppMethodBeat.i(methodId)方法

@Override
protected void onMethodEnter() {
    TraceMethod traceMethod = collectedMethodMap.get(methodName);
    if (traceMethod != null) {
        traceMethodCount.incrementAndGet();
        mv.visitLdcInsn(traceMethod.id);
        mv.visitMethodInsn(INVOKESTATIC, TraceBuildConstants.MATRIX_TRACE_CLASS, "i", "(I)V", false);
    }
}