Eclipse plugin 如何使用ASTRewrite插入/更新使用JDT的方法体?

Eclipse plugin 如何使用ASTRewrite插入/更新使用JDT的方法体?,eclipse-plugin,eclipse-jdt,Eclipse Plugin,Eclipse Jdt,我想使用JDT的ASTRewrite在方法内部编写代码。我尝试使用ASTRewrite,但它不起作用。请帮忙。我的ASTRewrite的示例代码如下: public void实现方法(MethodDeclaration methodToBeImplemented){ AstfMethod=methodToBeImplemented.getAST(); ASTRewrite ASTRewrite=ASTRewrite.create(astfmethod); 块体=astfmethod.newBlo

我想使用JDT的ASTRewrite在方法内部编写代码。我尝试使用ASTRewrite,但它不起作用。请帮忙。我的ASTRewrite的示例代码如下:

public void实现方法(MethodDeclaration methodToBeImplemented){
AstfMethod=methodToBeImplemented.getAST();
ASTRewrite ASTRewrite=ASTRewrite.create(astfmethod);
块体=astfmethod.newBlock();
方法实施。立位体(体);
MethodInvocation newMethodInvocation=astOfMethod.newMethodInvocation();
QualifiedName name=astfmethod.newQualifiedName(astfmethod
.newSimpleName(“系统”),astOfMethod.newSimpleName(“输出”);
newMethodInvocation.setExpression(名称);
newMethodInvocation.setName(astOfMethod.newSimpleName(“println”));
ExpressionStatement ExpressionStatement=asofmethod.newExpressionStatement(newMethodInvocation);
body.statements().add(expressionStatement);
astRewrite.set(oldBody,MethodDeclaration.BODY_属性,BODY,null);
ctcObj.document=新文档(ctcObj.source);
edit=astRewrite.rewriteAST(ctcObj.document,null);
试一试{
编辑.应用(ctcObj.文件);
}catch(格式错误的tree异常){
e、 printStackTrace();
}捕获(错误位置异常e){
e、 printStackTrace();
}
}

我尝试使用不同类型的ASTRewrite.set(),但它要么生成编译时错误,说参数非法,要么生成运行时异常。

您还需要一个步骤:写入文件。编辑(应用)不写入文件。 示例见: (由于缺少
旧体的声明,我在下面的声明中假设是正确的。)


必须删除以下行:

methodToBeImplemented.setBody(body);
在上面这一行中,您可以手动更改一个节点,该节点应该是
ASTRewrite
的目标。通常不建议这样做

接下来是你的电话

astRewrite.set(oldBody, MethodDeclaration.BODY_PROPERTY, body, null);
失败,因为目标节点(第一个参数)和目标节点属性(第二个参数)必须与节点类匹配。但在您的例子中,它是
Block(oldBody)
MethodDeclaration(BODY\u属性)
。正确的电话是:

astRewrite.set(methodToBeImplemented, MethodDeclaration.BODY_PROPERTY, body, null);

ASTRewrite.set()
的另一种解决方案是调用:

astRewrite.replace(oldBody, body, null);

下次,请在发布之前清理代码。这次我把它擦干净了,但它很难读。