2014-10-11 36 views
4

有人可以给我澄清visit方法的第二个参数arg的用法,如JavaParser documentation example page的以下代码所示?

我在互联网上找不到任何信息。JavaParser访问方法arg参数澄清

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

回答

3

这很简单。

当您与访问者联系时,您可以提供此附加参数,然后将其传回给访问者的visit方法。这基本上是将一些上下文对象传递给访问者的一种方式,允许访问者自己保持无状态。例如,考虑一个你想收集访问时看到的所有方法名称的情况。您可以提供一个Set<String>作为参数并向该集添加方法名称。我想这是它背后的基本原理。 (我个人更喜欢有状态的游客)。

顺便说一句,你通常应该叫

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

不是倒过来。