harshit modani
harshit modani

Reputation: 141

How to get list of methods defined in another class called from a given method in Java

I am planning to get list of methods defined in one package(CommonPackage) called by a class defined in another package (ServicePackage). For that, I need a to crawl a given method code and get the methods called outside of this class.

I have researched the Java reflections and was not able to find any solution for this. I also went through How to get the list of methods called from a method using reflection in C# and was not able to find any conclusive solution for JAVA specifically.

ClassA {
    private ClassB classB;
    public methodA1(){
        classB.methodB1();
    }
}

ClassB {

    public methodB1(){
      // Some code
    }
}

Expected: For ClassA.MethodA1, we get the list of methods called inside it. Output: ClassB.MethodB1

Upvotes: 5

Views: 346

Answers (2)

harshit modani
harshit modani

Reputation: 141

I used an open source byte code manipulator called Javassists which already has an API to fetch method calls made in a given method. It also has method to fetch the code attribute which can give you the no of lines in a given method.

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.NotFoundException;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;
public static void main(String[] args)
{
    ClassPool cp = ClassPool.getDefault();
    CtClass ctClass = null;
    try {
        ctClass = cp.get(className);
    } catch (NotFoundException e) {
        throw new RuntimeException(e);
    }

    CtMethod ctMethod = ctClass.getMethod(methodName);

    ctMethod.instrument( 
           new ExprEditor() {
               public void edit(MethodCall calledMethod) {
                   System.out.println("Method "+ calledMethod.getMethod().getName() + " is called inside "+methodName);
           }
    });
}

Upvotes: 2

AlexR
AlexR

Reputation: 115328

Reflection API provides visibility of class structure: its methods and fields. It does not allow however to look into methods.

What you need is to parse the byte code generated by compiler and extract interesting information from there. There are number of libraries that do this, e.g. Apache BCEL. You can take a look on similar question and relevant answer in SO.

Upvotes: 4

Related Questions