Java源代码解析器: Need to find access modifiers of declared field variables

标签 java eclipse parsing global-variables

我有一个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/

相关文章:

将小程序放置到网站上时出现 java.lang.reflect.inspirationtargetException 错误

java - 使用 Java 检测 ETX 字符

java - 字符串选择和分配

node.js - 解析 Post 表单数据 Node.js Express

java - 如何为 Java 中的每个类字段创建 JSON 对象列表

java - Eclipse 代码完成 : Is it possible to select a method without the parameters?

java - Eclipse 中的 Checkstyle 错误 - 无法实例化 Tab 字符

Java 类路径失败但 Eclipse 可以工作

python - PLY yacc解析IF-ELSE IF-ELSE嵌套语句

c++ - 为模拟解析数据文件的优雅方式