我想嵌入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(...)注入的。现在有一个问题:
name (例如String name;),那么绑定没有效果,因为该变量已经存在于脚本中。name。问题是:如何解决这个问题?如何告诉类型检查器,当调用脚本时,脚本将接收特定类型的全局变量?
发布于 2017-08-09 15:58:30
在文档中,可以使用extensions参数,
config.addCompilationCustomizers(
new ASTTransformationCustomizer(
TypeChecked,
extensions:['robotextension.groovy'])
)然后将robotextension.groovy添加到类路径中:
unresolvedVariable { var ->
if ('name'==var.name) {
storeType(var, classNodeFor(String))
handled = true
}
}这里,我们告诉编译器,如果找到了一个未解决的变量,并且变量的名称是name,那么我们可以确保这个变量的类型是String。
https://stackoverflow.com/questions/45594683
复制相似问题