How transform VariableDeclarationStatement to ExpressionStatement using AST [message #727599] |
Wed, 21 September 2011 11:42  |
Eclipse User |
|
|
|
Hi,
I have an object that is used in many methods, so I want to have its declaration on class scope and keep its current behavior, in other words I want to add a fixture.
Getting from this:
public String method1() {
StringBuilder sb = new StringBuilder("test1");
return sb.toString();
}
to that:
private StringBuilder sb;
public String method1() {
sb = new StringBuilder("test1"); //problem is to keep semicolumn;
return sb.toString();
}
Taking the example above the user will select StringBuilder to do the refactoring.
Doing so, for core.dom.AST the selection will be a VariableDeclarationStatement, inside this object there is a VariableDeclarationFragment wich is almost what I need, it brings "sb = new StringBuilder("test1")" whithout semicolumn, I need to concat a semicolumn to this object to replace the original VariableDeclarationStatement becoming in a ExpressionStatement.
Can anyone please help me?
thanks
|
|
|
|
Re: How transform VariableDeclarationStatement to ExpressionStatement using AST [message #729055 is a reply to message #728596] |
Sat, 24 September 2011 17:51  |
Eclipse User |
|
|
|
Just in case someone needs the same thing, here is the answer.
The problem was in the ClassInstanceCreation I should use setType intead of setName.
private void testAssignement2(ASTNode node) {
// get AST block
Block blkParent = (Block) node.getParent();
// STATEMENT: MISSING = MISSING
Assignment a = blkParent.getAST().newAssignment();
a.setOperator(Assignment.Operator.ASSIGN);
// STATEMENT: this.varName = MISSING
FieldAccess fa = blkParent.getAST().newFieldAccess();
fa.setExpression(blkParent.getAST().newThisExpression());
fa.setName(blkParent.getAST().newSimpleName("varName"));
a.setLeftHandSide(fa);
// STATEMENT: new StringBuilder()
ClassInstanceCreation cic = null;
cic = blkParent.getAST().newClassInstanceCreation();
cic.setType( blkParent.getAST().newSimpleType(blkParent.getAST().newSimpleName("StringBuilder") ));
// STATEMENT: this.varName = new StringBuilder()
a.setRightHandSide(cic);
// ENCAPSULATE THE ASSIGNEMENT INSERTING A SEMICOLUMN
// STATEMENT: this.varName = new MISSING();
ExpressionStatement ess = blkParent.getAST().newExpressionStatement(a);
setASTObject(ess);
}
|
|
|
Powered by
FUDForum. Page generated in 0.07325 seconds