开发者社区> 问答> 正文

获取方法中的所有变量名

我想在Java文件的所有方法中检索所有变量名。像Person.java包含的示例

class Person {
    private String firstName;
    private String lastName;
    public static void main() {
            String test = "test";
            Person p1 = new Person();
            p1.setName("John");
    }
    public void setName(String name)   {
            this.firstName = name;
    }

}

我希望能够打印出所有声明的变量。我尝试使用javaparser检索它们。但是,我只能检索在类中声明的变量

firstName

lastName 我也希望能够检索在main方法中声明的所有变量

firstName lastName test 我的javaparser方法是

public static void getVariables(String inputFilePath) {
    try {
        CompilationUnit cu = StaticJavaParser.parse(new File(inputFilePath));

        cu.findAll(FieldDeclaration.class).forEach(field -> {
            field.getVariables().forEach(variable -> {
                System.out.println(variable.getName());
                variable.getInitializer().ifPresent(initValue -> 
                System.out.println(initValue.toString()));
            });
        });
    } catch (FileNotFoundException fe) {
        System.out.println(fe.getMessage());
    } catch (IOException e){
        System.out.println(e.getMessage());
    }

}

解决了

按照Eugene的建议,我现在可以检索所有变量

public static void getVariables(String inputFilePath) {
    try {
        CompilationUnit cu = StaticJavaParser.parse(new File(inputFilePath));
        cu.findAll(VariableDeclarator.class).forEach(variable -> {
            System.out.println(variable);
        });
    } catch (FileNotFoundException fe) {

    } catch (IOException e) {

    }
}

问题来源:Stack Overflow

展开
收起
montos 2020-03-27 16:38:44 590 0
1 条回答
写回答
取消 提交回答
  • 你传入FieldDeclaration.class到CompilationUnit的的findAll()方法。因此,按照要求,它将获取所有已声明的字段。

    如果要列出所有声明的变量,请VariableDeclarator.class在同一包中使用–它会为您提供所有这些变量,包括声明为字段的变量。

    回答来源:Stack Overflow

    2020-03-27 16:39:02
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载