谁能给我解释一下 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/