Get all variable names in methods

user3413646 :

I would like to retrieve all variable names in all methods of a java file. Example Like a Person.java contains

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

}

i would like to be able to print out all variables declared. I have tried using javaparser to retrieve them. However, i can only retrieve variables declared in the class which is

firstName

lastName

I want to be able to retrieve all variables declared in main method as well

firstName
lastName
test

My javaparser method is

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

}

Solved

As following Eugene's suggestion, i am able to retrieve all variables now

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) {

    }
}
Eugene :

You are passing FieldDeclaration.class into CompilationUnit's findAll() method. So, as asked, it gets you all declared fields.

If you want to list all declared variables, use VariableDeclarator.class from the same package – it will get you all of those, including the ones declared as fields.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=291592&siteId=1