如何创建带有参数的函数调用语句并添加函数

How to create FunctionCall statement with arguments and add in function

本文关键字:函数调用 语句 函数 添加 参数 何创建 创建      更新时间:2023-09-26

我需要创建像Utiliy.initialize("value")这样的FunctionCall语句,并将其添加到js文件每个函数的第一行。

下面是我尝试创建函数调用的代码

private FunctionCall getFunctionCall() {
        FunctionCall functionCall = new FunctionCall();
        Name name =  new Name();
        name.setIdentifier("initialize");
        functionCall.setTarget(name);
}

下面是我用来在每个函数节点中添加的代码

class FunctionVisitor implements NodeVisitor {
        @Override
        public boolean visit(AstNode node) {
             if (node.getClass() == FunctionNode.class) {
                FunctionNode fun = (FunctionNode) node;
                fun.addChildrenToFront(getFunctionCall());
            }
            return true;
        }
    }

请建议如何创建带有参数的函数调用以及如何打印创建的函数调用语句进行测试。是否有任何工具可用于查看javascript节点,如java ASTVIEW查看器?

您必须创建 StringLiteral 作为参数并将其添加到 functionCall,在这种情况下,它可以是 NumberLiteral、ArrrayLiteral 等(参见:http://javadox.com/org.mozilla/rhino/1.7R4/org/mozilla/javascript/ast/AstNode.html)

private FunctionCall getFunctionCall() {
        FunctionCall functionCall = new FunctionCall();
        Name name =  new Name();
        name.setIdentifier("initialize");
        functionCall.setTarget(name);
        StringLiteral arg = new StringLiteral();
        arg.setValue("value");
        arg.setQuoteCharacter('"');
        functionCall.addArgument(arg);
        return functionCall;
}
class FunctionVisitor implements NodeVisitor {
        @Override
        public boolean visit(AstNode node) {
             if (node.getClass() == FunctionNode.class) {
                FunctionNode fun = (FunctionNode) node;
                if(fun.getName().equals("initialize")) //prevents infinit loop
                {
                     return true;
                }
                fun.getBody().addChildrenToFront(new EmptyStatement()); // adds ';', I don't know if required
                fun.getBody().addChildrenToFront(getFunctionCall());//no fun.addChildrenToFront
            }
            return true;
        }
    }

您可以通过toSource()方法打印每个corect AstNode。我希望这会有所帮助。