如何查找调用了哪些 Method 方法并在其中声明了变量

How to find which Method methods are invoked from and variables are declared within

我正在尝试将声明的变量和调用的方法映射到它们所在的位置 declared/invoked。我正在开发一个独立的应用程序。

这是我目前的情况:

public class HelloWorld {
  static ArrayList methodsDeclared = new ArrayList();
  static ArrayList methodsInvoked = new ArrayList();
  static ArrayList variablesDeclared = new ArrayList();

  public static void main(String[] args) {
  ...

  public static void parse(String file) {
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(file.toCharArray());
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
    cu.accept(new ASTVisitor() {

      public boolean visit(MethodDeclaration node) {
        methodsDeclared.add(node);
        return false;
      }

      public boolean visit(MethodInvocation node) {
        methodsInvoked.add(node);
        return false;
      }

      public Boolean visit(VariableDeclarationFragment node) {
        variablesDeclared.add(node);
        return false;
      }
    }
  }
}

到最后,我有 3 个包含我需要的信息的 ArrayList。文件中的方法、声明的变量和调用的方法。我希望能够具体找到在哪些方法中定义了哪些变量(如果不是 class 变量)以及从哪些方法调用了哪些方法。有什么想法吗?

首先,您需要 space 来存储变量 "X" 位于方法 "Y" 内的信息。您需要将 methodsDeclared 的类型从 ArrayList (无论如何都应该包含泛型)更改为 Map<MethodDeclaration, Set<VariableDeclarationFragment>>.

static final Map<MethodDeclaration, Set<VariableDeclarationFragment>> methodDeclared = new HashMap<MethodDeclaration, Set<VariableDeclarationFragment>>();

MethodDeclaration 的访问者方法中,在此字段中输入 add/create 一个新条目。

HelloWorld.methodDeclared.put(node, new HashSet<VariableDeclarationFragment>());

VariableDeclarationFragment 类型的访问者方法中,您将变量声明添加到此变量声明所在的方法声明中。您需要 getParent() 方法来查找方法声明。然后使用此信息访问 Map 中的正确条目并将变量声明添加到集合中。

// find the method declaration from the "node" variable
MethodDeclaration methodOfVariable = FindMethodDeclaration(node); // node is of type "VariableDeclarationFragment"
// add the node to the method declaration
HelloWorld.methodDeclared.get(methodOfVariable).add(node);

Note: You have to write such a FindMethodDeclaration or check the API if there is such a helper method.

获得 运行 代码后,字段 methodDeclared 将包含键中的每个方法声明,值将包含变量声明。