How to use ASTRewrite for inserting/updating body of the method using JDT?
I want to write code inside the method using JDT's ASTRewrite. I tried using ASTRewrite but its not working. Kindly help. Sample code of my ASTRewrite is below:
public void implementMethod(MethodDeclaration methodToBeImplemented) {
astOfMethod = methodToBeImplemented.getAST();
ASTRewrite astRewrite = ASTRewrite.create(astOfMethod);
Block body = astOfMethod.newBlock();
methodToBeImplemented.setBody(body);
MethodInvocation newMethodInvocation = astOfMethod.newMethodInvocation();
QualifiedName name = astOfMethod.newQualifiedName(astOfMethod
.newSimpleName("System"), astOfMethod.newSimpleName("out"));
newMethodInvocation.setExpression(name);
newMethodInvocation.setName(astOfMethod.newSimpleName("println"));
ExpressionStatement expressionStatement = astOfMethod.newExpressionStatement(newMethodInvocation);
body.statement开发者_开发百科s().add(expressionStatement);
astRewrite.set(oldBody, MethodDeclaration.BODY_PROPERTY, body, null);
ctcObj.document = new Document(ctcObj.source);
edit = astRewrite.rewriteAST(ctcObj.document, null);
try {
edit.apply(ctcObj.document);
} catch (MalformedTreeException e) {
e.printStackTrace();
} catch (BadLocationException e) {
e.printStackTrace();
}
}
I tried using different types of ASTRewrite.set() but it generates either compile time error saying illegal parameters or run time exceptions.
You need one more step: Write to file. edit(apply) does not write to file. Example see: Rewrite method incorrectly rewrite change to ICompilationUnit the second rewrite update
(As the declaration of oldBody
is missing I'm assuming in the following a correct declaration.)
The following line must be removed:
methodToBeImplemented.setBody(body);
With the above line you manually changing a node which should be a target of ASTRewrite
. Usually that is not recommended.
Next, your call
astRewrite.set(oldBody, MethodDeclaration.BODY_PROPERTY, body, null);
fails because the target node (1st parameter) and target node property (2nd parameter) must be matching regarding the node class. But in your case it is Block (oldBody)
and MethodDeclaration (BODY_PROPERTY)
. A proper call is:
astRewrite.set(methodToBeImplemented, MethodDeclaration.BODY_PROPERTY, body, null);
An alternative solution to ASTRewrite.set()
would be this call:
astRewrite.replace(oldBody, body, null);
精彩评论