Eclipse Astrewrite Example - Android
What is ASTRewrite in eclipse?
Snippet Code
ASTRewrite in eclipse is generally known as set of class which is used to make changes in existing AST(Abstract Syntax Tree). The sample code for ASTRewrite is given 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.statements().add(expressionStatement);
astRewrite.set(methodToBeImplemented, 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();
}
}
Tags