簡體   English   中英

如何使用javaparser獲取類級別的變量聲明?

[英]How to get class level variable declarations using javaparser ?

我只想獲取類級別的變量聲明。 如何使用javaparser獲取聲明?

public class Login {

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

使用javaparser必須獲取變量“ browser”的詳細信息,例如瀏覽器的類型為“ KeyWord”

不太確定我是否理解您的問題-您想讓班上所有的現場成員嗎? 如果是這樣,您可以這樣做:

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());
        }  
    }
}

在您的情況下,將顯示以下代碼示例:關鍵字瀏覽器字符串頁面標題“登錄”

我希望這確實是您的問題...如果沒有,請發表評論。

要將以上答案更新為最新版本的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()));
    });
});

兩者之間的功能差異在於,第一個僅在頂級類中查找,而第二個也將在嵌套類中查找。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM