JavaParser访问方法arg参数说明

标签 java javaparser

谁能给我解释一下 visit 方法的第二个参数 arg 的用法,如以下来自 JavaParser documentation example page 的代码所示?

我在互联网上找不到任何信息。

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

最佳答案

这很简单。

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

例如,假设您想收集访问时看到的所有方法名称。您可以提供 Set<String>作为参数并将方法名称添加到该集合。我想这就是它背后的基本原理。 (我个人更喜欢有状态访问者)。

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

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

反之则不然。

关于JavaParser访问方法arg参数说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26309761/

相关文章:

java - Java中的黄金分割

java - 如何测试这条 Camel 路线?依赖注入(inject)和环境变量

java - 使用 url 表达式

java - 解析字符串以获取分组参数

java - 如何返回 DocumentSnapShot 作为方法的结果?

java - 如何只获取字符串的最后一个字母而不是整个字符串

体式 json 数据的 JAVA 解析器 "Error:JSONObject cannot be converted to JSONArray"

java - 在 inria Spoon 中构建模型的更快方法

JavaParser - 获取类型 AST

JavaSymbolSolver:获取字段的完全限定名称