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.
<pre><code> String foo = "bar"; </code></pre>
-
George Gastaldi
-
mahmoud abdeen
-
Saulius
-
clace