Question

Im trying to add arguments to the arguments list of a MethodInvocation and it doesnt seem to work, I can remove objects but I cant see to add them. My end goal is to take 2 MethodInvocation that invoke the same method with different arguments and convert it to 1 MethodInvocation that has a ConditionalExpression as an argument. Example:

if (A){
   System.out.println("hi");
} else {
   System.out.println("hey");
}

Will be converted to:

System.out.println((A ? "hi" : "hey"));

So I would also appreciate it if someone knwos how to convert the argument list to 1 big Expression I can place in the ConditionalExpression.

Thanks!

EDIT: sorry forgot to mention is it a code formatting plug-in for ecplise

EDIT2: the code I am trying to run:

final ExpressionStatement thenStmnt=(ExpressionStatement)((Block)node.getThenStatement()).statements().get(0),
            elseStmnt=(ExpressionStatement)((Block)node.getElseStatement()).statements().get(0);
MethodInvocation thenMethod=(MethodInvocation)thenStmnt.getExpression(),
                elseMethod=(MethodInvocation)elseStmnt.getExpression();
final MethodInvocation method=ast.newMethodInvocation();
method.setName(ast.newSimpleName("add"));
method.arguments().add(0, elseMethod.arguments().get(0));

ast is a given leagal AST and node is a given leagal IfStatement.

Was it helpful?

Solution

Solved, problem was here:

method.arguments().add(0, elseMethod.arguments().get(0));

If you want to take or copy something that is already part of your original code, meaning already exist in the AST you have to use r.createCopyTarget, like so:

method.arguments().add(0, r.createCopyTarget(elseMethod.arguments().get(0)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top