Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get class level variable declarations using javaparser ?

I want to get only the class level variable declarations. How can i get the declarations using javaparser?

public class Login {

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

Using javaparser have to get the details of variable "browser" like the type of browser is "KeyWord"


1 Answers

Not quite sure i understood your question - do you want to get all the field-members of a class? if so you can do it like this:

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

This code example will print in your case: Keyword browser String pageTitle "Login"

I hope this was really your question... if not, please comment.

like image 190
poozmak Avatar answered Dec 15 '25 12:12

poozmak