How to use ASTRewrite to update/add contents to a method? [message #715015] |
Fri, 12 August 2011 05:22  |
Eclipse User |
|
|
|
public void implementMethod(){
astOfMethod=methodToBeImplemented.getAST();
ASTRewrite astRewrite= ASTRewrite.create(astOfMethod);
Block body=astOfMethod.newBlock();
methodToBeImplemented.setBody(body);
Block oldBody=methodToBeImplemented.getBody();
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.statements().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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Note: In above code, the statement System.out.println() gets added to the body of the method. Because when I print methodToBeImplemented, I get the statement in the body of method. But Its not getting reflected in the document object.
In above code there is exception getting generated "IllegalArgumentException" for astRewrite.set method. I am not whether i did use it correctly or not?
Kindly help. Files are attached for reference. Input2.java is source file to be parsed. 2) Heuristics.java : above code is present in this file 3) ASTModifier.java : Visitor pattern for finding different nodes in AST. 4) ContractToCode.java: Main file to be executed.
|
|
|
|
|
|
Powered by
FUDForum. Page generated in 0.02758 seconds