如何获取从 Java 中的给定方法调用的另一个 class 中定义的方法列表

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

我打算获取一个包 (CommonPackage) 中定义的方法列表,这些方法由另一个包 (ServicePackage) 中定义的 class 调用。为此,我需要爬取给定的方法代码并获取在此 class 之外调用的方法。

我研究了 Java 反射,但无法找到任何解决方案。我也经历了 How to get the list of methods called from a method using reflection in C#,但无法找到 JAVA 的任何决定性解决方案。

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

ClassB {

    public methodB1(){
      // Some code
    }
}

预期:对于ClassA.MethodA1,我们得到了其中调用的方法列表。输出:ClassB.MethodB1

反射 API 提供 class 结构的可见性:其方法和字段。但是,它不允许查看方法。

您需要的是解析编译器生成的字节码并从中提取有趣的信息。有许多库可以执行此操作,例如Apache BCEL. You can take a look on similar question and relevant answer in SO

我使用了一个名为 Javassists 的开源字节码操纵器,它已经有一个 API 来获取在给定方法中进行的方法调用。它还具有获取代码属性的方法,该属性可以为您提供给定方法中的行数。

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);
           }
    });
}