我有一个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;
}
关于Java源代码解析器: Need to find access modifiers of declared field variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18711356/