AST eclipse,向MethodInvocation添加参数



我试图将参数添加到MethodInvocation的参数列表中,它似乎不起作用,我可以删除对象,但我看不到添加它们。我的最终目标是采用2个MethodInvocation(使用不同的参数调用相同的方法),并将其转换为1个MethodInvocation(使用ConditionalExpression作为参数)。例子:

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

将被转换为:

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

所以如果有人知道如何将参数列表转换为我可以放在ConditionalExpression中的1个大表达式,我也会很感激。

谢谢!

编辑:抱歉忘了说这是一个代码格式化插件的eclipse

编辑2:我要运行的代码:

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是给定的合法ast, node是给定的合法IfStatement。

解决了,问题在这里:

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

如果你想获取或复制一些已经是你的原始代码的一部分,意思是已经存在于AST中,你必须使用r.createCopyTarget,像这样:

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

最新更新