Вы можете попробовать эту тему
, вам следует взглянуть на org.eclipse.jdt.core
плагин и особенно ASTParser
класс там.
Просто для запуска синтаксического анализатора будет достаточно следующего кода:
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT); // you tell parser, that source is whole java file. parser can also process single statements
parser.setSource(source);
CompilationUnit cu = (CompilationUnit) parser.createAST(null); // CompilationUnit here is of type org.eclipse.jdt.core.dom.CompilationUnit
// source is either char array, like this:
public class A { int i = 9; int j; }".toCharArray()
//org.eclipse.jdt.core.ICompilationUnit type, which represents java source files
в рабочей области.
после построения AST,Вы можете просмотреть его с посетителем, который расширяет ASTVisitor
, например:
cu.accept(new ASTVisitor() {
public boolean visit(SimpleName node) {
System.out.println(node); // print all simple names in compilation unit. in our example it would be A, i, j (class name, and then variables)
return true;
}
});
Подробнее и пример кода в этой теме
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(compilationUnit);
parser.setSourceRange(method.getSourceRange().getOffset(), method.getSourceRange().getLength());
parser.setResolveBindings(true);
CompilationUnit cu = (CompilationUnit)parser.createAST(null);
cu.accept(new ASTMethodVisitor());