Question

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);
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top