Hicks48
Hicks48

Reputation: 105

Java ASM finding concrete implementing class

I'm new to java byte coding and I have been struggling with this problem for a while. I'm using java ASM bytecode engineering library. I would like to find all methods and classes where those methods are implemented that a particular method calls. Name and description of the called method and name of the class that implements called method. The problem is that when a method that is being analyzed calls method that is defined in an interface or abstract class I cant find the name of the concrete class that actually implements the called method. Here is also some of my code and test output that visualizes situation.

public class MyClassVisitor extends ClassVisitor {    
       public List<MethodCallers> methodCallers;

       public MyClassVisitor() {
           super(Opcodes.ASM4);
           this.methodCallers = new ArrayList<>();
       }

       @Override
       public MethodVisitor visitMethod(int access, String name, String desc, String        signature, String[] exceptions) {
            MethodCallers methodData = new MethodCallers(name, desc);
            this.methodCallers.add(methodData);
            return new MyMethodVisitor(methodData);
        }
}

 public class MyMethodVisitor extends MethodVisitor {
        private final MethodCallers methodCallers;

    public MyMethodVisitor(MethodCallers methodCallers) {
        super(Opcodes.ASM4);
        this.methodCallers = methodCallers;
    }

    @Override
    public void visitMethodInsn(int opcode, String owner, String name, String desc) {
        String implementingClass = owner;

        if(opcode == Opcodes.INVOKEINTERFACE) {
            /* Here I would need to find the concrete implementing class */
            /* implementingClass = something */
        }

        this.methodCallers.addCaller(new CalledMethod(name, desc, implementingClass));
    }
 }

public static void main(String[] args) throws Exception {
        ClassReader classReader = new ClassReader("TestClass");
        MyClassVisitor classVisitor = new MyClassVisitor();

        classReader.accept(classVisitor, 0);
        //...
}

and the output:

Name: Description: ()V Called these methods called name: Desc: in class java/lang/Object called name: Desc: in class java/util/ArrayList

Name: increment Description: (I)V

Called these methods called name: valueOf Desc: valueOf in class java/lang/Integer

called name: add Desc: add in class java/util/List /* Here I would like to see ArrayList instead of List */

All help will be appreciated!

Upvotes: 0

Views: 1354

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533520

To find the concrete class you need to look at the extends class or implements interfaces When you find these classes in the header, you need to look up those classes in turn and possibly their parents as well.

Upvotes: 0

Related Questions