5

有人可以给我澄清一下方法的第二个参数的用法,argJavaParser 文档示例页面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());
        }
    }
}
4

1 回答 1

5

这很简单。

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

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

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

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

不是相反。

于 2014-10-11T00:30:26.873 回答