如何在JDT Eclipse中从字符串构建树?

时间:2019-01-21 15:51:22

标签: java eclipse-jdt

我通过jDT编译器以字符串形式获取AST:
MethodDeclaration ArrayType SimpleType SimpleName对象SimpleName方法SingleVariableDeclaration PrimitiveType int SimpleName x块VariableDeclarationStatement PrimitiveType int VariableDeclarationFragment SimpleName y IfStatement NumberLiteral ReturnStatement NumberLiteral ReturnStatement InfixExpression + SimpleName xNumberLiteral

方法:

Object[] method(int x) {
     int y;
     if(1)
        return 1;
     else
        return x+3;
 }

如何将上面的AST字符串转换为树,这可以帮助我通过任何方法在这棵树上遍历?

这是我的代码:

    srcCode = "class t { Object[] method(int x) {int y;if(1)return 1;else return x+3;}}";
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(srcCode.toCharArray());
    parser.setResolveBindings(true);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);
    final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    cu.accept(new ASTVisitor() {
        @Override
        public boolean visit(MethodDeclaration node) {
            ast += node.getClass().getSimpleName() + " ";
            return true;
        }

        @Override
        public boolean visit(VariableDeclarationFragment node) {
            // System.out.println(node.getClass().getSimpleName());
            ast += node.getClass().getSimpleName() + " ";
            return true;
        }

        @Override
        public boolean visit(TypeDeclaration node) {
            // System.out.println(node.getClass().getSimpleName());
            return true;
        }

        @Override
        public boolean visit(SimpleName node) {
            // System.out.println("----> "+node.getClass().getSimpleName() + " " + node);
            ;
            ast += node.getClass().getSimpleName() + " " + node ;

            List<ASTNode> children = getChildren(node);
            // System.out.println(node.getIdentifier());
            return false;
        }

        public boolean visit(ReturnStatement node) {
            // System.out.println(node.getClass().getSimpleName());
            ast += node.getClass().getSimpleName() + " ";
            System.out.println(node.getParent().getParent());

            ASTNode parentNode = node.getParent();

            // tree.addNode(node.getClass().getSimpleName(),);
            return true;
        }

        public boolean visit(SingleVariableDeclaration node) { //
            System.out.println(node.getClass().getSimpleName());
            ast += node.getClass().getSimpleName() + " ";
            return true;
        }

所有子类的依此类推

0 个答案:

没有答案