Embedded Groovy: How to use static type checking with external variables?

Viewed 767

I want to embed Groovy to enable scripting capabilities in my Java application. I want to use static type checking, and in addition I want to pass some additional (global) variables to the script. Here is my configuration:

    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();

As you can see, the user-provided script uses the global variable name, which is injected via script.setBinding(...). Now there is a problem:

  • If I declare the variable name in the user script (e.g. String name;), then the binding has no effect because the variable already exists in the script.
  • If I do not declare the variable in the script, the static type checker will (rightfully) complain that name was not declared.

The question is: how do I solve this? How can I tell the type checker that the script will receive a global variable of a certain type when it is called?

1 Answers
Related