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

Posted

技术标签:

【中文标题】如何确定 Eclipse JDT 中方法或字段的修饰符?【英文标题】:How to determine the modifiers for a method or field in Eclipse JDT? 【发布时间】:2012-01-20 17:09:47 【问题描述】:

我正在为 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;
    

【问题讨论】:

【参考方案1】:

如文档所述,调用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

【讨论】:

【参考方案2】:

还有另外一种辅助方法modifiers(),它为您提供了您的方法所具有的修饰符列表。要查看是否为final,可以直接查看该列表。

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

【讨论】:

以上是关于如何确定 Eclipse JDT 中方法或字段的修饰符?的主要内容,如果未能解决你的问题,请参考以下文章

在 CDT 之上安装 Eclipse JDT

.settings/org.eclipse.jdt.core.prefs 是项目的一部分吗?

centos 配置eclipse jdt和cdt

greenDao 报错org.eclipse.jdt.internal.compiler.impl.CompilerOptions.versionToJdkLevel(Ljava/lang/Objec

Compilation err ororg.eclipse.jdt.internal.compiler.classfmt.ClassFormatException

Compilation err ororg.eclipse.jdt.internal.compiler.classfmt.ClassFormatException