Arosha Mudalige
Arosha Mudalige

Reputation: 75

How to get class level variable names using javaparser?

I was able to get class level variable's declarations using the following code. But I only need the variable name. This is the output I get for following code - [private boolean flag = true;]

import com.github.javaparser.JavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import java.io.FileInputStream;

public class CuPrinter{
    public static void main(String[] args) throws Exception {
        // creates an input stream for the file to be parsed
        FileInputStream in = new FileInputStream("C:\\Users\\arosh\\IdeaProjects\\Bot_Twitter\\src\\MyBot.java");

        CompilationUnit cu;
        try {
            // parse the file
            cu = JavaParser.parse(in);
        } finally {
            in.close();
        }
        cu.accept(new ClassVisitor(), null);
}
private static class ClassVisitor extends VoidVisitorAdapter<Void> {
    @Override
    public void visit(ClassOrInterfaceDeclaration n, Void arg) {
        /* here you can access the attributes of the method.
         this method will be called for all methods in this
         CompilationUnit, including inner class methods */
        System.out.println(n.getFields());
        super.visit(n, arg);
    }
  }
}

Upvotes: 5

Views: 2515

Answers (2)

WSS
WSS

Reputation: 513

You can try this. If you have more than one variables in FieldDeclarations, use one more for loop inside.

public void visit(ClassOrInterfaceDeclaration n, Void arg) {

    super.visit(n, arg);
    for(FieldDeclaration ff:n.getFields())
    {
        System.out.println(ff.getVariable(0).getName());
    }
} 

Upvotes: 2

Lino
Lino

Reputation: 19926

You can use the following simple regex:

final String regex = "^((private|public|protected)?\\s+)?.*\\s+(\\w+);$";

Which then can be compiled into a Pattern:

final Pattern pattern = Pattern.compile(regex);

And then finally be used in a for-loop:

for(final String field : n.getFields()){
    // create a regex-matcher
    final Matcher matcher = pattern.matcher(field);

    // if field matches regex
    if(matcher.matches()){
        // get the last group -> the fieldName
        final String name = matcher.group(matcher.groupCount());
        System.out.println("FieldName: " + name);
    }
}

Upvotes: 4

Related Questions