How to add a new statement on the same line using JavaParser

566 Views Asked by At

I know that JavaParser operates on the AST, yet I was curious if it was possible to add new statements on the same line as another one. Let me give an example on what I would like to achieve.

Example input X.java (do not mind the "logic"):

public class X {
    public static void main(String[] args) {
        int a = 1;
        while(a < 100) {
            a *= 2;
        }
    }
}

What I would like to achieve is to add the statement System.out.println("End of loop reached"); at the end of every loop body - yet, if possible, I would like to add this new statement next to the last statement in the body. Thus, the result should look something like this:

public class X {
    public static void main(String[] args) {
        int a = 1;
        while(a < 100) {
            a *= 2; System.out.println("End of loop reached");
        }
    }
}

Currently I use the following visitor (written in Kotlin), just to get to know JavaParser. Yet this results in new lines being added for the print statements. Any idea on how to instruct JavaParser to add new nodes on the same line?

class WhileVisitor : VoidVisitorAdapter<Void>() {
    override fun visit(whileStatement: WhileStmt, arg: Void?) {
        super.visit(whileStatement, arg)
        val oldBody = whileStatement.body
        if (oldBody.isBlockStmt) {
            (oldBody as BlockStmt).addStatement("System.out.println(\"End of loop reached\");")
        } else {
            whileStatement
                .createBlockStatementAsBody()
                .addStatement(oldBody)
                .addStatement("System.out.println(\"End of loop reached\");")
        }
    }
}
0

There are 0 best solutions below