使用eclipse JDT / AST添加一个新方法

时间:2014-03-20 14:19:21

标签: eclipse abstract-syntax-tree eclipse-jdt

我能够遍历TypeDeclaration,我只想在其上添加一个简单的方法。我怎么做?我试过下面的代码片段,但没有用。

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 个答案:

答案 0 :(得分:1)

您可以通过以下代码获取第一个TypeDeclaration的List Rewriter来实现:

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

你去。