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.
This is the sample case for parsing:
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);
}
}
}
This is the code I write to parse the above sample case:
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");
}
});
}
}
When I use it to parse the code, it can only get the result that method getName(), setName(), getAge() and getAge() have been visited while main() is ignored.
Looking forward to your answers. Thanks.