[英]Eclipse JDT ASTVisitor - how to tell if a field is read or written in a method?
[英]How to determine the modifiers for a method or field in Eclipse JDT?
我正在為Eclipse JDT編寫一些簡單的AST訪問者。 我有一個MethodVisitor
和FieldVisitor
類,每個類都擴展了ASTVisitor
。 以MethodVisitor
為例。 在該類的Visit
方法(這是一個覆蓋),我能夠找到每個MethodDeclaration
節點。 當我有其中一個節點時,我想查看它的Modifiers
,看它是public
還是private
(也可能是其他修飾符)。 有一個名為getModifiers()
的方法,但我不清楚如何使用它來確定應用於特定MethodDeclaration
的修飾符的類型。 我的代碼發布在下面,如果您有任何想法如何繼續,請告訴我。
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;
}
}
正如文檔所述,調用getModifiers()
的結果是相關Modifier
常量的getModifiers()
位“或”。 例如,如果你想知道方法是否是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
}
還有一個輔助方法modifiers()
,它為您提供了方法所具有的修飾符列表。 要檢查它是否是final
,您可以直接簽入該列表。
for(Object o : methodDeclarationNode.modifiers()) {
if(o.toString().equals("final")) {
return true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.