1
votes

I am able to traverse upto TypeDeclaration, and I just want to add a simple method onto it. How do I do that? I have tried below code snippet but didn't work.

AST ast = compilationUnit.getAST();
for (final TypeDeclaration typeDeclaration : allTypes) {
        MethodDeclaration methodNode = typeDeclaration.getAST()
                .newMethodDeclaration();

        // methodNode.parameters();
        methodNode.setName(ast.newSimpleName("test"));

        Block block = ast.newBlock();
        ListRewrite listRewrite = rewriter.getListRewrite(block,
                Block.STATEMENTS_PROPERTY);
        Statement statement = (Statement) rewriter
                .createStringPlaceholder("//New Edited \n ",
                        ASTNode.EMPTY_STATEMENT);
        listRewrite.insertLast(statement, null);
        methodNode.setBody(block);
}
1

1 Answers

1
votes

You can do it by getting List Rewriter of first TypeDeclaration by following code:

    ListRewrite lrw = astRewriter.getListRewrite(((TypeDeclaration)compilationUnit.types().get(0)), TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
    lrw.insertLast(methodDeclaration, null);

There you go.