Dong Qiu
Dong Qiu

Reputation: 43

Using Eclipse JDT to parse java files

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.

Upvotes: 2

Views: 4221

Answers (2)

Unni Kris
Unni Kris

Reputation: 3105

There seems to problem with the code you are using to read the source.

Try this code below to read the file :

File javaFile = new File(filePath);
BufferedReader in = new BufferedReader(new FileReader(javaFile));
final StringBuffer buffer = new StringBuffer();
String line = null;
while (null != (line = in.readLine())) {
     buffer.append(line).append("\n");
}

and use this to set your parser source :

parser.setSource(buffer.toString().toCharArray());

Everything else seems to be fine with the code.

Upvotes: 1

Deepak Azad
Deepak Azad

Reputation: 7923

The problem is that your readCharFromFile(filePath) method removes \n or end-of-line characters from the file. This means that all lines after the comment are actually part of the comment.

Upvotes: 1

Related Questions