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

时间:2017-07-29 12:47:28

标签: java abstract-syntax-tree

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

这是我到目前为止所拥有的:

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个ArrayLists,其中包含我需要的信息。文件中的方法,声明的变量和调用的方法。我希望能够具体找到哪些变量在哪些方法中定义(如果不是类变量)以及从哪些方法调用哪些方法。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

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

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

MethodDeclaration类型的访问者方法中,您可以在此字段中添加/创建新条目。

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

VariableDeclarationFragment类型的visitor方法中,将变量声明添加到此变量声明所在的方法声明中。您需要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);
  

注意:如果有这样的辅助方法,您必须编写这样的FindMethodDeclaration或检查API。

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

相关问题