3

我正在爲Eclipse JDT編寫一些簡單的AST訪問者。我有一個MethodVisitorFieldVisitor類,每個類擴展ASTVisitor。以MethodVisitor爲例。在該類'Visit方法(這是一個覆蓋)中,我能夠找到MethodDeclaration節點中的每一個節點。當我有其中一個節點時,我想查看其Modifiers以查看它是否爲publicprivate(也可能是其他修改器)。有一種方法稱爲getModifiers(),但我不清楚如何使用它來確定應用於特定MethodDeclaration的修飾符的類型。我的代碼發佈在下面,如果您有任何想法,請告訴我如何繼續。如何確定Eclipse JDT中方法或字段的修飾符?

import java.util.ArrayList; 
import java.util.List; 

import org.eclipse.jdt.core.dom.ASTVisitor; 
import org.eclipse.jdt.core.dom.MethodDeclaration; 

public class MethodVisitor extends ASTVisitor { 

    private List<MethodDeclaration> methods; 

    // Constructor(s) 
    public MethodVisitor() { 
     this.methods = new ArrayList<MethodDeclaration>(); 
    } 

    /** 
    * visit - this overrides the ASTVisitor's visit and allows this 
    * class to visit MethodDeclaration nodes in the AST. 
    */ 
    @Override 
    public boolean visit(MethodDeclaration node) { 
     this.methods.add(node); 

      //*** Not sure what to do at this point *** 
      int mods = node.getModifiers(); 

     return super.visit(node); 
    } 

    /** 
    * getMethods - this is an accessor methods to get the methods 
    * visited by this class. 
    * @return List<MethodDeclaration> 
    */ 
    public List<MethodDeclaration> getMethods() { 
     return this.methods; 
    } 
} 

回答

11

隨着文檔狀態,調用getModifiers()的結果是按位「或」相關Modifier常量。因此,舉例來說,如果你想找出方法是否是final你會使用:

int modifiers = node.getModifiers(); 
if (modifiers & Modifier.FINAL != 0) { 
    // It's final 
} 

或者您可以使用在Modifier類的便利方法:

int modifiers = node.getModifiers(); 
if (Modifier.isFinal(modifiers)) { 
    // It's final 
} 
0

有一個輔助方法modifiers()它給你你的方法有修飾符的列表。要檢查它是否爲final,可以直接檢入該列表。

for(Object o : methodDeclarationNode.modifiers()) { 
    if(o.toString().equals("final")) { 
     return true; 
    } 
}