5

Could someone give me clarification on the usage of the second argument arg of the visit method as shown in the following code from the JavaParser documentation example page ?

I can't find any information on the internet.

public class MethodPrinter {

    public static void main(String[] args) throws Exception {
        // creates an input stream for the file to be parsed
        FileInputStream in = new FileInputStream("test.java");

        CompilationUnit cu;
        try {
            // parse the file
            cu = JavaParser.parse(in);
        } finally {
            in.close();
        }

        // visit and print the methods names
        new MethodVisitor().visit(cu, null);
    }

    /**
     * Simple visitor implementation for visiting MethodDeclaration nodes. 
     */
    private static class MethodVisitor extends VoidVisitorAdapter {

        @Override
        public void visit(MethodDeclaration n, Object 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.getName());
        }
    }
}
Heisenberg
  • 53
  • 3

1 Answers1

5

It is quite simple.

When you call accept method with your visitor, you can provide this additional argument, which will then be passed back to the visit methods of your visitor. This is a basically a way of passing some context object to the visitor allowing the visitor itself to stay stateless.

For instance, consider a case where you'd like to gather all the method names you see while visiting. You could provide a Set<String> as an argument and add method names to that set. I guess this is the rationale behind it. (I personally prefer stateful visitors instead).

By the way, you should normally call

cu.accept(new MethodVisitor(), null);

not the other way round.

lexicore
  • 42,748
  • 17
  • 132
  • 221