问题描述
如果我们从一个类创建一个对象,然后在编译时调用它的方法并将其添加到 AST 树中,我们应该使用什么样的节点?
例如:new PasswordFormate().format();
这个节点在 AST 中的类型是什么?
AST 中这个节点的子节点类型是什么?
解决方法
您可以通过实现 ASTVisitor 来了解 AST 的“外观”。 ASTVisitors 有一个名为 preVisit
(和 postVisit
)的方法,您可以使用它以您喜欢的任何形式(例如相应 ASTNode-Object 的类)打印 AST。
看看这个:http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html
我将通过使用上述两种方法实现 ASTVisitor 并将树打印为字符串来解决它。然后就可以看到用到了哪些ASTNode类。
要启动已实现的 AST 访问者,请使用访问方法:
ASTParser astParser = ASTParser.newParser(AST.JLS8); // Or use whatever constant applies here
astParser.setKind(ASTParser.K_COMPILATION_UNIT);
astParser.setSource(unit);
astParser.setResolveBindings(true); // maybe false,depending on your use case?
CompilationUnit compilationUnit = (CompilationUnit) astParser.createAST(null);
ASTVisitor astPrintingVisitor = new ASTPrinter(); // you need to implement this
compilationUnit.visit(astPrintingVisitor);