代码之家  ›  专栏  ›  技术社区  ›  Martin Häusler

嵌入式Groovy:如何使用外部变量的静态类型检查?

  •  3
  • Martin Häusler  · 技术社区  · 9 年前

    我想嵌入Groovy,以便在Java应用程序中实现脚本功能。我想使用静态类型检查,此外,我想向脚本传递一些额外的(全局)变量。这是我的配置:

        String script = "println(name)";  // this script was entered by the user
    
        // compiler configuration for static type checking
        CompilerConfiguration config = new CompilerConfiguration();
        config.addCompilationCustomizers(new ASTTransformationCustomizer(CompileStatic.class));
    
        // compile the script
        GroovyShell shell = new GroovyShell(config);
        Script script = shell.parse(script);
    
        // later, when we actually need to execute it...
        Binding binding = new Binding();
        binding.setVariable("name", "John");
        script.setBinding(binding);
        script.run();
    

    name script.setBinding(...) .现在有一个问题:

    • 如果我声明变量 名称 String name; 绑定无效 因为变量已经存在于脚本中。
    • 名称

    问题是:

    1 回复  |  直到 9 年前
        1
  •  1
  •   aristotll    9 年前

    doc , 您可以使用 extensions 参数

    config.addCompilationCustomizers(
        new ASTTransformationCustomizer(
            TypeChecked,
            extensions:['robotextension.groovy'])
    )
    

    robotextension.groovy 到您的类路径:

    unresolvedVariable { var ->
        if ('name'==var.name) {
            storeType(var, classNodeFor(String))
            handled = true
        }
    }
    

    未解析变量 名称 ,然后我们可以确保该变量的类型为 String