2014-10-11 124 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); 

不是倒過來。