How to determine the modifiers for a method or field in Eclipse JDT?

2.7k Views Asked by At

I am writing some simple AST visitors for the Eclipse JDT. I have a MethodVisitor and FieldVisitor class which each extend the ASTVisitor. Take the MethodVisitor for instance. In that class' Visit method (which is an override), I am able to find each of the MethodDeclaration nodes. When I have one of those nodes, I want to look at its Modifiers to see whether it is public or private (and perhaps other modifiers as well). There is a method called getModifiers(), but it is unclear to me how to use this to determine the type of modifier applied to the particular MethodDeclaration. My code is posted below, please let me know if you have any ideas how to proceed.

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;
    }
}
2

There are 2 best solutions below

0
On BEST ANSWER

As the documentation states, the result of calling getModifiers() is a bit-wise "or" of the relevant Modifier constants. So for example, if you want to find out whether or not the method is final you'd use:

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

Or you can use the convenience methods in the Modifier class:

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

There is one more helper method modifiers() which gives you the list of modifiers your method has. To check whether it is final or not, you can directly check in that list.

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