Eclipse JDT tutorial: Parse a Java method by using ASTParser

This tutorial belongs to Eclipse JDT Tutorial Series.

ASTParser can use its setKind() method to set source to be parsed as a compilation unit, single expression, a sequence of statements, or a sequence of class body declarations.

parser.setKind(ASTParser.K_COMPILATION_UNIT);

Any of those four can not handle a single independent method. This is not pleasant. Following the logic of a compilation unit, a class can be parsed. So we can add a fake class name as a shell to each method, then the method wrapped in a fake class can be parsed correctly by using ASTParser.

The code looks like this:

String sourceStart = "public class A {";
//add a fake class A as a shell, to meet the requirement of ASTParser
String sourceMiddle = "";
for(String s : tempMiddle){	
	s = s.trim();
	if(s.trim().length()>0 && !s.startsWith("---") && !s.startsWith("/") && !s.startsWith("*") )
	sourceMiddle += s.trim() + "\n";
}
String sourceEnd = "}";
 
String source = sourceStart + sourceMiddle + sourceEnd;
 
parser.setSource(source.toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
 
cu.accept(new ASTVisitor() {
        //by add more visit method like the following below, then all king of statement can be visited.
	public boolean visit(ForStatement node) {
 
	System.out.println("ForStatement -- content:" + node.toString());
 
	ArrayList<Integer> al = new ArrayList<Integer>();
	al.add(node.getStartPosition());
	al.add(node.getLength());
 
	statements.add(al);
	return false;
}
 
      	/*
	IfStatement
	ForStatement
	WhileStatement
	DoStatement
	TryStatement
	SwitchStatement
	SynchronizedStatement
	*/
}

There may be a better way to do this, but surely this works and it is much better than writing a parser from scratch.

Cheers.

Here is a post about using JDT ASTParser to parse a class which resides in a .java file.

Category >> Java Development Tools (JDT)  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • George Gastaldi

    There is Roaster, which uses Eclipse JDT and provides a nice abstraction API on top of that: https://github.com/forge/roaster

  • mahmoud abdeen

    hi .. i wont to know how to get the declaration of parameters in the method and the number of using of each parameters inside the method .. can you help me??

  • Saulius

    I’ve tried this. Not sure there was a need to eliminate comments, I just used IMethod.getSource() as sourceMiddle. However, node.resolveMethodBinding() would return null in Visitor, which was unacceptable for me. Instead I pass method to Visitor constructor and then check if this is the method I need to analyze. It’s rather complex pattern though :/

  • clace

    Hi Admin,
    I’ve read your post about ASTParser Class, I’m interesting to know about how can I do to read a java class file and get its attribute, methods, dependency in general, please if you can to write me, thanks a lot!