1

我只想获得类级别的变量声明。如何使用 javaparser 获取声明?

public class Login {

    private Keyword browser;
    private String pageTitle = "Login";
}

使用 javaparser 必须获取变量“浏览器”的详细信息,例如浏览器的类型是“关键字”

4

2 回答 2

8

不太确定我是否理解你的问题 - 你想获得一个班级的所有现场成员吗?如果是这样,您可以这样做:

CompilationUnit cu = JavaParser.parse(javaFile);
for (TypeDeclaration typeDec : cu.getTypes()) {
    List<BodyDeclaration> members = typeDec.getMembers();
    if(members != null) {
        for (BodyDeclaration member : members) {
        //Check just members that are FieldDeclarations
        FieldDeclaration field = (FieldDeclaration) member;
        //Print the field's class typr
        System.out.println(field.getType());
        //Print the field's name 
        System.out.println(field.getVariables().get(0).getId().getName());
        //Print the field's init value, if not null
        Object initValue = field.getVariables().get(0).getInit();
        if(initValue != null) {
             System.out.println(field.getVariables().get(0).getInit().toString());
        }  
    }
}

此代码示例将在您的情况下打印:Keyword browser String pageTitle "Login"

我希望这真的是你的问题......如果不是,请发表评论。

于 2014-04-08T13:09:47.787 回答
3

要将上述答案更新为最新版本的 JavaParser:

CompilationUnit cu = JavaParser.parse("public class Login {\n" +
        "\n" +
        "    private Keyword browser;\n" +
        "    private String pageTitle = \"Login\";\n" +
        "}\n");

for (TypeDeclaration<?> typeDec : cu.getTypes()) {
    for (BodyDeclaration<?> member : typeDec.getMembers()) {
        member.toFieldDeclaration().ifPresent(field -> {
            for (VariableDeclarator variable : field.getVariables()) {
                //Print the field's class typr
                System.out.println(variable.getType());
                //Print the field's name
                System.out.println(variable.getName());
                //Print the field's init value, if not null
                variable.getInitializer().ifPresent(initValue -> System.out.println(initValue.toString()));
            }
        });
    }
}

一种不费吹灰之力地进行现场声明的方法是......

cu.findAll(FieldDeclaration.class).forEach(field -> {
    field.getVariables().forEach(variable -> {
        //Print the field's class typr
        System.out.println(variable.getType());
        //Print the field's name
        System.out.println(variable.getName());
        //Print the field's init value, if not null
        variable.getInitializer().ifPresent(initValue -> System.out.println(initValue.toString()));
    });
});

两者的功能区别在于第一个只在顶级类中查找,第二个也将在嵌套类中查找。

于 2018-06-04T18:08:37.603 回答