我有一个Java类源代码。我需要解析代码并找出字段变量声明及其访问修饰符的列表。
目前,我正在为Eclipse JDT写一些简单的AST访问器。我有以下代码来获取声明的变量:
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;
}
但是,没有与上述类型VariableDeclarationFragment相关的方法。还有其他类型,例如SingleVariableDeclaration和VariableDeclarationExpression,但是它们不提供类字段声明的变量。他们只给方法局部变量。
请让我知道是否还有其他方法可以执行此操作,以便获得字段变量的访问修饰符。提前致谢!
最佳答案
在以下代码的帮助下,可以检索修饰符:
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;
}