hussam mutlq
hussam mutlq

Reputation: 21

how to build a for statement in AST using java parser?

I am using java parser and I want to build a for statement in a certain method such as the main method. I could write a statement that prints on screen

(System.out.println("hello world") 

but I could not build a for statement.

Upvotes: 1

Views: 1477

Answers (1)

issamux
issamux

Reputation: 1415

i'm using project com.github.javaparser :

public static void main(String[] args) {

    // creates an input stream for the file to be parsed
    FileInputStream in;
    try {
        in = new FileInputStream("test.java");
        try {
            // parse the file
            CompilationUnit cu = JavaParser.parse(in);
            new MyMethodVisitor().visit(cu, null);
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            in.close();

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

//Method visitor

 private static class MyMethodVisitor extends VoidVisitorAdapter {

    @Override
    public void visit(MethodDeclaration method, Object arg) {
        //
        System.out.println("method body : " + method.toString());
        System.out.println("*******************************");
        //
        addForStmt(method.getBody());
        //
        System.out.println("method body : " + method.toString());
        //
    }

    private void addForStmt(BlockStmt body) {

        int beginLine = body.getBeginLine();
        int beginColumn = body.getBeginColumn();
        int endLine = body.getEndLine();
        int endColumn = body.getEndColumn();
        //
        List<Expression> init = new ArrayList<Expression>();
        Expression compare = null;
        List<Expression> update = null;
        BlockStmt methodBody = new BlockStmt();
        ForStmt forStmt = new ForStmt(beginLine, beginColumn, endLine, endColumn, init, compare, update, methodBody);
        //
        ASTHelper.addStmt(body, forStmt);
    }

}

output:

[Before]

method body : public void forStatementMethod() {}

[After]

method body : public void forStatementMethod() {
for (; ; ) {
}
}

//test.java

public class test<E> {

public void forStatementMethod() {
}
}

Sample Project in github:issamux

Upvotes: 2

Related Questions