Reputation: 1309
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!
Upvotes: 0
Views: 1113
Reputation: 959
After cast and get the return of getModifiers() like said by @kajarigd, use a binary comparison with constants of org.eclipse.jdt.core.dom.Modifier class to determine what modifiers are in the int value returned.
For exemple, to know if the declaration has the modifier "public" on it, use:
if ((modifiers & Modifier.PUBLIC) > 0) {
...<has the public identifier, and may have others>
}
if ((modifiers & Modifier.PUBLIC) == 0) {
...<does NOT have the public identifier, but may have others>
}
if ((modifiers & Modifier.PUBLIC & Modifier.SYNCHRONIZED) > 0) {
...<has the public AND the synchronized modifier, and may have others>
}
In other words, each bit of the int value is like a flag turned on (1) or off (0) to determine witch modifiers the declaration has.
(probably my English need some review, feel free to do that...)
Upvotes: 0
Reputation: 1309
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;
}
Upvotes: 1