我能够遍历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);
}
答案 0 :(得分:1)
您可以通过以下代码获取第一个TypeDeclaration的List Rewriter来实现:
ListRewrite lrw = astRewriter.getListRewrite(((TypeDeclaration)compilationUnit.types().get(0)), TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
lrw.insertLast(methodDeclaration, null);
你去。