JavaParser访问方法arg参数澄清

Hei*_*erg 5 java javaparser

arg有人可以向我澄清该方法的第二个参数的用法,如JavaParser 文档示例页面visit中的以下代码所示吗? 我在互联网上找不到任何信息。

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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

lex*_*ore 5

这很简单。

当您使用accept访问者调用方法时,您可以提供此附加参数,然后该参数将被传递回visit访问者的方法。这基本上是一种将某些上下文对象传递给访问者的方法,允许访问者本身保持无状态。

例如,考虑这样一种情况,您希望收集访问时看到的所有方法名称。您可以提供 aSet<String>作为参数并将方法名称添加到该集合中。我想这就是其背后的原理。(我个人更喜欢有状态的访问者)。

顺便说一句,你通常应该打电话

cu.accept(new MethodVisitor(), null);
Run Code Online (Sandbox Code Playgroud)

反之则不然。