简体   繁体   English

使用JDT Eclipse获取Java方法的抽象语法树

[英]Get Abstract Syntax tree for Java method using JDT Eclipse

I'm working on a project that must use Eclipse JDT for parsing java methods and generating Abstract Syntax tree for them I wrote the following code : 我正在一个必须使用Eclipse JDT来解析Java方法并为其生成抽象语法树的项目上,我编写了以下代码:

String method ="\n"+
    "   public void sayHello() {\n"+
    "   System.out.println(\"Hello \"+name+\"!\");\n"+
    "   }\n";
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(method.toCharArray());
parser.setResolveBindings(true);
parser.setBindingsRecovery(true);
CompilationUnit unit = (CompilationUnit)parser.createAST(null);

This snippet just creates AST, but I get stuck!! 这个片段只是创建了AST,但是我被卡住了!! I'd like to visit AST of any java method and print its path. 我想访问任何Java方法的AST并打印其路径。 Can I get print AST for java Method? 我可以为java方法获取打印AST吗?

Eclipse AST (as most AST actually) exploit the visitor pattern extensively. Eclipse AST(就像大多数AST一样)广泛地利用了访问者模式。

So from the point you are, all you have to do is to instantiate a visitor, and make it visit the compilation unit. 因此,从您的角度出发,您要做的就是实例化一个访问者,并使其访问编译单元。 It will then automatically navigate fields, methods, annotations... 然后它将自动导航字段,方法,注释...

For your specific need, I think you can start with the following code: 对于您的特定需求,我认为您可以从以下代码开始:

unit.accept(new ASTVisitor() {

    @Override
    public boolean visit(MethodDeclaration node) {
        Type ownerTypeNode = (Type) node.getParent();
        System.out.println("Found method " + node.getName().getFullyQualifiedName() " + " in type " + ownerTypeNode.getName().getFullyQualifiedName());
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM