[英]How to find which Method methods are invoked from and variables are declared within
我試圖將聲明的變量和調用的方法映射到聲明/調用它們的位置。 我正在開發一個獨立的應用程序。
這是我到目前為止的內容:
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以及所需的信息。 文件中的方法,聲明的變量和調用的方法。 我希望能夠專門找到在哪些方法(如果不是類變量)中定義了哪些變量,以及從哪些方法中調用了哪些方法。 有任何想法嗎?
首先,您需要一個空間,用於存儲變量“ X”位於方法“ Y”內部的信息。 您需要將ArrayList
中methodsDeclared
的類型更改為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
類型的訪問者方法中,將變量聲明添加到該變量聲明所在的方法聲明中。您需要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
將包含鍵中的每個方法聲明,而值將包含變量聲明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.