kajarigd kajarigd - 19 days ago 6
Java Question

Java source code parser: Need to find access modifiers of declared field variables

I have a java class source code. I need to parse the code and find out the list of field variable declarations along with their access modifiers.

At present I am am writing some simple AST visitors for the Eclipse JDT. I have the following code to get the declared variables:

cu.accept(new ASTVisitor() {
public boolean visit(VariableDeclarationFragment node) {
SimpleName name = node.getName();
System.out.println("Declaration of '"+name+"' at line"+cu.getLineNumber(name.getStartPosition()));
return false;
}


But there is no method associated with with the above type VariableDeclarationFragment. There are other types like SingleVariableDeclaration and VariableDeclarationExpression, but they don't give the class field declared variables. They give only the method local variables.

Please let me know if there is any other way to do this thing, so that I can get the access modifiers of the field variables. Thanks in advance!

Answer

With the help of the following code, the modifier can be retrieved:

public boolean visit(VariableDeclarationFragment node) {
                    SimpleName name = node.getName();
                    System.out.println("Declaration of '"+name+"' at line"+cu.getLineNumber(name.getStartPosition()));

                    int modifiers = 0;
                    if (node.getParent() instanceof FieldDeclaration){
                        modifiers = ((FieldDeclaration)node.getParent()).getModifiers();
                    }
                    else if (node.getParent() instanceof VariableDeclarationStatement){
                        modifiers = ((VariableDeclarationStatement)node.getParent()).getModifiers();
                    }
                    return false; 
                }
Comments