繁体   English   中英

从JAVA中提取AST并将AST打印到文件中

[英]Extracting AST from JAVA and printing the AST to a file

我是Java编程语言的初学者。 我想从java源代码中提取AST并将AST打印到文件或标准输出。

我按照本教程学习如何使用AST。 http://www.programcreek.com/2011/01/a-complete-standalone-example-of-astparser/

所以根据我到目前为止的代码如下。

import java.util.HashSet;
import java.util.Set;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;

public class Test {
    public static void main(String args[]){
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setSource("public class A { int i = 9;  \n int j; \n ArrayList<Integer> al = new ArrayList<Integer>();j=1000; }".toCharArray());
        //parser.setSource("/*abc*/".toCharArray());
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        //ASTNode node = parser.createAST(null);


        final CompilationUnit cu = (CompilationUnit) parser.createAST(null);

    }
}

我尝试使用以下代码片段将其打印到标准输出,但它没有给出我预期的结果,

System.out.println(cu.getAST().toString());

如果有人可以帮助我将AST打印到文件中,那将是一个很大的帮助。

提前致谢。

以下是将AST转换为JSON的示例 您可以修改JSONStyleASTPrinter.java文件以生成XML而不是JSON等。

基于如何训练JDT Dragon的例子.pdf

private void print(ASTNode node) {
    List properties = node.structuralPropertiesForType();
    for (Iterator iterator = properties.iterator(); iterator.hasNext();) {
        Object descriptor = iterator.next();
        if (descriptor instanceof SimplePropertyDescriptor) {
            SimplePropertyDescriptor simple = (SimplePropertyDescriptor) descriptor;
            Object value = node.getStructuralProperty(simple);
            System.out.println(simple.getId() + " (" + value.toString() + ")");
        } else if (descriptor instanceof ChildPropertyDescriptor) {
            ChildPropertyDescriptor child = (ChildPropertyDescriptor) descriptor;
            ASTNode childNode = (ASTNode) node.getStructuralProperty(child);
            if (childNode != null) {
                System.out.println("Child (" + child.getId() + ") {");
                print(childNode);
                System.out.println("}");
            }
        } else {
            ChildListPropertyDescriptor list = (ChildListPropertyDescriptor) descriptor;
            System.out.println("List (" + list.getId() + "){");
            print((List) node.getStructuralProperty(list));
            System.out.println("}");
        }
    }
}

private void print(List nodes) {
    for (Iterator iterator = nodes.iterator(); iterator.hasNext();) {
        print((ASTNode) iterator.next());
    }
}

暂无
暂无

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

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