title: Using Eclipse JDT to parse java files
body: <p>I use Eclipse JDT library to parse java source code to visit all methods defined in classes. When the code contains comment like "//xxxx" in the body of the method, the parser will stop before the comment, and the method main(String[] args) was ignored. </p>
  
  <p>This is the sample case for parsing:</p>
  
  <pre><code>public class HelloWorld {
  
      private String name;
      private int age; 
  
      public String getName() {
          return name;
      }
  
      public void setName(String name) {
          this.name = name;
      }
  
      public int getAge() {
          return age;
      }
  
      public void setAge(int age) {
                  //Set the age
          this.age = age;
          System.out.println();
      }
  
      public static void main(String[] args) {
  
          HelloWorld hw = new HelloWorld();
          if(true) {
              hw.setAge(10);
          }
  
      }
  }
  </code></pre>
  
  <p>This is the code I write to parse the above sample case:</p>
  
  <pre><code>public class Parser {
  
  /**
   * Parse java program in given file path
   * @param filePath
   */
  public void parseFile(String filePath) {
      System.out.println("Starting to parse " + filePath);
      char[] source = readCharFromFile(filePath);
      ASTParser parser = ASTParser.newParser(AST.JLS3);
      parser.setKind(ASTParser.K_COMPILATION_UNIT);
      parser.setSource(source);
      parser.setResolveBindings(true);
      CompilationUnit cu = (CompilationUnit) parser.createAST(null);
  
      cu.accept(new ASTVisitor() {
  
          @Override
          public boolean visit(MethodDeclaration node) {
              return true;
          }
  
          @Override
          public void endVisit(MethodDeclaration node) {
              System.out.println("Method " + node.getName().getFullyQualifiedName() + " is visited");
          }
  
      });
  }
  }
  </code></pre>
  
  <p>When I use it to parse the code, it can only get the result that method <code>getName()</code>, <code>setName()</code>, <code>getAge()</code> and <code>getAge()</code> have been visited while <code>main()</code> is ignored.  </p>
  
  <p>Looking forward to your answers. Thanks.</p>