英文:
Avoiding reinitialsation of groovy shell for each record
问题
for(int i = 0; i < records.length; i++){
Binding binding=new Binding();
binding.setVariable("val1",records[i][0]);
binding.setVariable("val2",records[i][1]);
binding.setVariable("val3",records[i][2]);
GroovyShell shell=new GroovyShell(binding);
Object value = shell.evaluate(code);
System.out.println(value.toString());
};
我不想为每个记录重复创建 GroovyShell,但我看不到其他选项。从我所了解的情况来看,我不能在同一个 GroovyShell 上提供新的绑定,因为绑定只能在创建 shell 时提供,不能在之后更改。
我尝试过在创建 GroovyShell 后更改绑定对象,但是会出现错误。
我是否有其他方法,可以避免为每个记录重新初始化 GroovyShell?我只想将变量 record[i][0]、recordi、record[i][2] 传递给 shell。
英文:
I am trying to implement the following code:-
for(int i = 0; i < records.length; i++){
Binding binding=new Binding();
binding.setVariable("val1",records[i][0]);
binding.setVariable("val2",records[i][1]);
binding.setVariable("val3",records[i][2]);
GroovyShell shell=new GroovyShell(binding);
Object value = shell.evaluate(code);
System.out.println(value.toString());
};
I don't want to create GroovyShell again and again for each record, but I am not able to see another option. From what I have seen, I can't provide a new binding to the same groovy shell, since binding can be provided only while creating the shell and not afterwards.
I have tried changing the binding object after creating groovy shell but it is giving me an error.
Do I have an alternative to reinitializing the groovy shell again and again for each record? I just want to pass the variables record[i][0],recordi,record[i][2] to the shell.
答案1
得分: 1
use [GroovyShell.parse(code)][1]
Script script = new GroovyShell().parse(code);
for(int i = 0; i < records.length; i++){
Binding binding=new Binding();
binding.setVariable("val1",records[i][0]);
binding.setVariable("val2",records[i][1]);
binding.setVariable("val3",records[i][2]);
script.setBinding(binding);
Object value = script.run();
System.out.println(value.toString());
};
<details>
<summary>英文:</summary>
use [GroovyShell.parse(code)][1]
Script script = new GroovyShell().parse(code);
for(int i = 0; i < records.length; i++){
Binding binding=new Binding();
binding.setVariable("val1",records[i][0]);
binding.setVariable("val2",recordsi);
binding.setVariable("val3",records[i][2]);
script.setBinding(binding);
Object value = script.run();
System.out.println(value.toString());
};
[1]: https://docs.groovy-lang.org/latest/html/api/groovy/lang/GroovyShell.html#parse(java.lang.String)
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论