有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将变量传递给扩展类的方法

我正在扩展类ClassVisitor,并重写方法visitMethod。然后我扩展MethodVisitor并覆盖visitMethodInsn。当我重写visitMethod时,我会创建扩展MethodVisitor的一个新实例

请参阅下面的代码以理解。要正确理解ASM库,需要了解ASM库

GraphClass。爪哇:

public class GraphClass extends ClassVisitor {
    public GraphClass() {
        super(ASM5);
    }

    public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
        System.out.println("testing " + name + desc);
        GraphMethod newVisitor = new GraphMethod();
        return newVisitor;
    }
}

作图法。爪哇:

public class GraphMethod extends MethodVisitor{
    public GraphMethod() {
        super(ASM5);
    }

    public void visitMethodInsn(int opcode, java.lang.String owner, java.lang.String name, java.lang.String descriptor, boolean isInterface) {
        System.out.println(owner + name);
    }
}

我试图做的是将visitMethod中的name变量与visitMethodInsn中的其他变量一起打印

我是Java新手,所以任何提示都会非常有用


共 (1) 个答案

  1. # 1 楼答案

    根据这些评论,我假设您想知道被访问类的方法调用了哪些方法,好吗

    使用objectweb asm的树api很容易解决这个问题

    ClassReader cr = new ClassReader(bytesOfSomeClass);
    //Used class node instead of visiter
    ClasaNode cn = new ClassNode(<asm version>);
    
    cr.accept(cn, 0);
    
    //Iterate all methods of class
    cn.methods.forEach( (MethodNode mn) -> {
        String callerName = mn.name;
    
        //Iterate all instructions of current method
        Stream.iterate(mn.instructions.getFirst(), AbstractInsnNode::getNext).limit(instructions.size())
            .filter(node -> node instanceof MethodInsnNode) //take only method calls
            .forEach(node -> {
                String calledName = ((MethodInsnNode) node).name;
                //Print results
                System.out.println(calledName + " is called by " + callerName);
             });
    });