簡體   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