如何确定Eclipse JDT中方法或字段的修饰符?

jbr*_*aud 3 java modifier abstract-syntax-tree visitor-pattern eclipse-jdt

我正在为Eclipse JDT编写一些简单的AST访问者.我有一个MethodVisitorFieldVisitor每个扩展的类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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 11

正如文档所述,调用的结果getModifiers()是相关Modifier常量的一个"或" .例如,如果您想知道该方法final是否使用:

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

或者您可以使用Modifier班级中的便捷方法:

int modifiers = node.getModifiers();
if (Modifier.isFinal(modifiers)) {
    // It's final
}
Run Code Online (Sandbox Code Playgroud)