Search code examples
javaparser

what is the functional difference between VoidVisitorAdapter and GenericVisitorAdapter in JavaParser


what is the functional difference between VoidVisitorAdapter and GenericVisitorAdapter in JavaParser. I am using both , but they seem to provide the same functionality .


Solution

  • In short, the visit methods of a GenericVisitorAdapter instance can have a return value of type R, while those of a VoidVisitorAdapter can't.

    public class MyVoidVisitor extends VoidVisitorAdapter<Void> {
        @Override
        public void visit(final ClassOrInterfaceDeclaration n, final Void arg) {
            // look into members
            super.visit(n, arg);
            // print the class name
            System.out.println(n.getNameAsString());
        }
    }
    
    public class MyGenericVisitor extends GenericVisitorAdaptor<List<String>, Void> {
        @Override
        public List<String> visit(final ClassOrInterfaceDeclaration n, final Void arg) {
            // look into members
            List<String> nestedClassNames = super.visit(n, arg);
            // accumulate the class name
            nestedClassNames.add(n.getNameAsString());
            return nestedClassNames;
        }
    }
    

    In the above example, the MyVoidVisitor can only print the class names into stdout because it doesn't have a return value. On the other hand, the MyGenericVisitor can accumulate nested class names into a list, which would then be returned to the caller.